RecipientEditTextView.java revision 4f82d888c680a61b95373740ce68bfb48a242617
1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.ex.chips; 18 19import android.app.Dialog; 20import android.content.ClipData; 21import android.content.ClipDescription; 22import android.content.ClipboardManager; 23import android.content.Context; 24import android.content.DialogInterface; 25import android.content.DialogInterface.OnDismissListener; 26import android.content.res.Resources; 27import android.content.res.TypedArray; 28import android.graphics.Bitmap; 29import android.graphics.BitmapFactory; 30import android.graphics.Canvas; 31import android.graphics.Matrix; 32import android.graphics.Point; 33import android.graphics.Rect; 34import android.graphics.RectF; 35import android.graphics.drawable.BitmapDrawable; 36import android.graphics.drawable.Drawable; 37import android.os.AsyncTask; 38import android.os.Handler; 39import android.os.Message; 40import android.os.Parcelable; 41import android.text.Editable; 42import android.text.InputType; 43import android.text.Layout; 44import android.text.Spannable; 45import android.text.SpannableString; 46import android.text.SpannableStringBuilder; 47import android.text.Spanned; 48import android.text.TextPaint; 49import android.text.TextUtils; 50import android.text.TextWatcher; 51import android.text.method.QwertyKeyListener; 52import android.text.style.ImageSpan; 53import android.text.util.Rfc822Token; 54import android.text.util.Rfc822Tokenizer; 55import android.util.AttributeSet; 56import android.util.Log; 57import android.util.Patterns; 58import android.view.ActionMode; 59import android.view.ActionMode.Callback; 60import android.view.DragEvent; 61import android.view.GestureDetector; 62import android.view.KeyEvent; 63import android.view.LayoutInflater; 64import android.view.Menu; 65import android.view.MenuItem; 66import android.view.MotionEvent; 67import android.view.View; 68import android.view.View.OnClickListener; 69import android.view.ViewParent; 70import android.view.inputmethod.EditorInfo; 71import android.view.inputmethod.InputConnection; 72import android.widget.AdapterView; 73import android.widget.AdapterView.OnItemClickListener; 74import android.widget.Button; 75import android.widget.ListAdapter; 76import android.widget.ListPopupWindow; 77import android.widget.ListView; 78import android.widget.MultiAutoCompleteTextView; 79import android.widget.ScrollView; 80import android.widget.TextView; 81 82import java.util.ArrayList; 83import java.util.Arrays; 84import java.util.Collection; 85import java.util.Collections; 86import java.util.Comparator; 87import java.util.HashMap; 88import java.util.HashSet; 89import java.util.Set; 90import java.util.regex.Matcher; 91 92/** 93 * RecipientEditTextView is an auto complete text view for use with applications 94 * that use the new Chips UI for addressing a message to recipients. 95 */ 96public class RecipientEditTextView extends MultiAutoCompleteTextView implements 97 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, 98 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener, 99 TextView.OnEditorActionListener { 100 101 private static final char COMMIT_CHAR_COMMA = ','; 102 103 private static final char NAME_WRAPPER_CHAR = '"'; 104 105 private static final char COMMIT_CHAR_SEMICOLON = ';'; 106 107 private static final char COMMIT_CHAR_SPACE = ' '; 108 109 private static final String TAG = "RecipientEditTextView"; 110 111 private static int DISMISS = "dismiss".hashCode(); 112 113 private static final long DISMISS_DELAY = 300; 114 115 // TODO: get correct number/ algorithm from with UX. 116 // Visible for testing. 117 /*package*/ static final int CHIP_LIMIT = 2; 118 119 private static final int MAX_CHIPS_PARSED = 50; 120 121 private static int sSelectedTextColor = -1; 122 123 // Resources for displaying chips. 124 private Drawable mChipBackground = null; 125 126 private Drawable mChipDelete = null; 127 128 private Drawable mInvalidChipBackground; 129 130 private Drawable mChipBackgroundPressed; 131 132 private float mChipHeight; 133 134 private float mChipFontSize; 135 136 private float mLineSpacingExtra; 137 138 private int mChipPadding; 139 140 private Tokenizer mTokenizer; 141 142 private Validator mValidator; 143 144 private RecipientChip mSelectedChip; 145 146 private int mAlternatesLayout; 147 148 private Bitmap mDefaultContactPhoto; 149 150 private ImageSpan mMoreChip; 151 152 private TextView mMoreItem; 153 154 private final ArrayList<String> mPendingChips = new ArrayList<String>(); 155 156 private Handler mHandler; 157 158 private int mPendingChipsCount = 0; 159 160 private boolean mNoChips = false; 161 162 private ListPopupWindow mAlternatesPopup; 163 164 private ListPopupWindow mAddressPopup; 165 166 private ArrayList<RecipientChip> mTemporaryRecipients; 167 168 private ArrayList<RecipientChip> mRemovedSpans; 169 170 private boolean mShouldShrink = true; 171 172 // Chip copy fields. 173 private GestureDetector mGestureDetector; 174 175 private Dialog mCopyDialog; 176 177 private String mCopyAddress; 178 179 /** 180 * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a 181 * selected chip. 182 */ 183 private OnItemClickListener mAlternatesListener; 184 185 private int mCheckedItem; 186 187 private TextWatcher mTextWatcher; 188 189 // Obtain the enclosing scroll view, if it exists, so that the view can be 190 // scrolled to show the last line of chips content. 191 private ScrollView mScrollView; 192 193 private boolean mTriedGettingScrollView; 194 195 private boolean mDragEnabled = false; 196 197 private final Runnable mAddTextWatcher = new Runnable() { 198 @Override 199 public void run() { 200 if (mTextWatcher == null) { 201 mTextWatcher = new RecipientTextWatcher(); 202 addTextChangedListener(mTextWatcher); 203 } 204 } 205 }; 206 207 private IndividualReplacementTask mIndividualReplacements; 208 209 private Runnable mHandlePendingChips = new Runnable() { 210 211 @Override 212 public void run() { 213 handlePendingChips(); 214 } 215 216 }; 217 218 private Runnable mDelayedShrink = new Runnable() { 219 220 @Override 221 public void run() { 222 shrink(); 223 } 224 225 }; 226 227 private int mMaxLines; 228 229 public RecipientEditTextView(Context context, AttributeSet attrs) { 230 super(context, attrs); 231 setChipDimensions(context, attrs); 232 if (sSelectedTextColor == -1) { 233 sSelectedTextColor = context.getResources().getColor(android.R.color.white); 234 } 235 mAlternatesPopup = new ListPopupWindow(context); 236 mAddressPopup = new ListPopupWindow(context); 237 mCopyDialog = new Dialog(context); 238 mAlternatesListener = new OnItemClickListener() { 239 @Override 240 public void onItemClick(AdapterView<?> adapterView,View view, int position, 241 long rowId) { 242 mAlternatesPopup.setOnItemClickListener(null); 243 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) 244 .getRecipientEntry(position)); 245 Message delayed = Message.obtain(mHandler, DISMISS); 246 delayed.obj = mAlternatesPopup; 247 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); 248 clearComposingText(); 249 } 250 }; 251 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 252 setOnItemClickListener(this); 253 setCustomSelectionActionModeCallback(this); 254 mHandler = new Handler() { 255 @Override 256 public void handleMessage(Message msg) { 257 if (msg.what == DISMISS) { 258 ((ListPopupWindow) msg.obj).dismiss(); 259 return; 260 } 261 super.handleMessage(msg); 262 } 263 }; 264 mTextWatcher = new RecipientTextWatcher(); 265 addTextChangedListener(mTextWatcher); 266 mGestureDetector = new GestureDetector(context, this); 267 setOnEditorActionListener(this); 268 mMaxLines = getLineCount(); 269 } 270 271 @Override 272 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) { 273 if (action == EditorInfo.IME_ACTION_DONE) { 274 if (commitDefault()) { 275 return true; 276 } 277 if (mSelectedChip != null) { 278 clearSelectedChip(); 279 return true; 280 } else if (focusNext()) { 281 return true; 282 } 283 } 284 return false; 285 } 286 287 @Override 288 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 289 InputConnection connection = super.onCreateInputConnection(outAttrs); 290 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION; 291 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) { 292 // clear the existing action 293 outAttrs.imeOptions ^= imeActions; 294 // set the DONE action 295 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 296 } 297 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) { 298 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION; 299 } 300 outAttrs.actionLabel = getContext().getString(R.string.done); 301 return connection; 302 } 303 304 /*package*/ RecipientChip getLastChip() { 305 RecipientChip last = null; 306 RecipientChip[] chips = getSortedRecipients(); 307 if (chips != null && chips.length > 0) { 308 last = chips[chips.length - 1]; 309 } 310 return last; 311 } 312 313 @Override 314 public void onSelectionChanged(int start, int end) { 315 // When selection changes, see if it is inside the chips area. 316 // If so, move the cursor back after the chips again. 317 RecipientChip last = getLastChip(); 318 if (last != null && start < getSpannable().getSpanEnd(last)) { 319 // Grab the last chip and set the cursor to after it. 320 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length())); 321 } 322 super.onSelectionChanged(start, end); 323 } 324 325 @Override 326 public void onRestoreInstanceState(Parcelable state) { 327 if (!TextUtils.isEmpty(getText())) { 328 super.onRestoreInstanceState(null); 329 } else { 330 super.onRestoreInstanceState(state); 331 } 332 } 333 334 @Override 335 public Parcelable onSaveInstanceState() { 336 // If the user changes orientation while they are editing, just roll back the selection. 337 clearSelectedChip(); 338 return super.onSaveInstanceState(); 339 } 340 341 /** 342 * Convenience method: Append the specified text slice to the TextView's 343 * display buffer, upgrading it to BufferType.EDITABLE if it was 344 * not already editable. Commas are excluded as they are added automatically 345 * by the view. 346 */ 347 @Override 348 public void append(CharSequence text, int start, int end) { 349 // We don't care about watching text changes while appending. 350 if (mTextWatcher != null) { 351 removeTextChangedListener(mTextWatcher); 352 } 353 super.append(text, start, end); 354 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) { 355 String displayString = text.toString(); 356 int separatorPos = displayString.lastIndexOf(COMMIT_CHAR_COMMA); 357 // Verify that the separator pos is not within ""; if it is, look 358 // past the closing quote. If there is no comma past ", this string 359 // will resolve to an error chip. 360 if (separatorPos > -1) { 361 String parseDisplayString = displayString.substring(separatorPos); 362 int endQuotedTextPos = parseDisplayString.indexOf(NAME_WRAPPER_CHAR); 363 if (endQuotedTextPos > separatorPos) { 364 separatorPos = parseDisplayString.lastIndexOf(COMMIT_CHAR_COMMA, 365 endQuotedTextPos); 366 } 367 } 368 if (!TextUtils.isEmpty(displayString) 369 && TextUtils.getTrimmedLength(displayString) > 0) { 370 mPendingChipsCount++; 371 mPendingChips.add(text.toString()); 372 } 373 } 374 // Put a message on the queue to make sure we ALWAYS handle pending 375 // chips. 376 if (mPendingChipsCount > 0) { 377 postHandlePendingChips(); 378 } 379 mHandler.post(mAddTextWatcher); 380 } 381 382 @Override 383 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { 384 super.onFocusChanged(hasFocus, direction, previous); 385 if (!hasFocus) { 386 shrink(); 387 } else { 388 expand(); 389 } 390 } 391 392 @Override 393 public void performValidation() { 394 // Do nothing. Chips handles its own validation. 395 } 396 397 private void shrink() { 398 if (mTokenizer == null) { 399 return; 400 } 401 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1; 402 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT 403 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) { 404 clearSelectedChip(); 405 } else { 406 if (getWidth() <= 0) { 407 // We don't have the width yet which means the view hasn't been drawn yet 408 // and there is no reason to attempt to commit chips yet. 409 // This focus lost must be the result of an orientation change 410 // or an initial rendering. 411 // Re-post the shrink for later. 412 mHandler.removeCallbacks(mDelayedShrink); 413 mHandler.post(mDelayedShrink); 414 return; 415 } 416 // Reset any pending chips as they would have been handled 417 // when the field lost focus. 418 if (mPendingChipsCount > 0) { 419 postHandlePendingChips(); 420 } else { 421 Editable editable = getText(); 422 int end = getSelectionEnd(); 423 int start = mTokenizer.findTokenStart(editable, end); 424 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 425 if ((chips == null || chips.length == 0)) { 426 Editable text = getText(); 427 int whatEnd = mTokenizer.findTokenEnd(text, start); 428 // This token was already tokenized, so skip past the ending token. 429 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') { 430 whatEnd = movePastTerminators(whatEnd); 431 } 432 // In the middle of chip; treat this as an edit 433 // and commit the whole token. 434 int selEnd = getSelectionEnd(); 435 if (whatEnd != selEnd) { 436 handleEdit(start, whatEnd); 437 } else { 438 commitChip(start, end, editable); 439 } 440 } 441 } 442 mHandler.post(mAddTextWatcher); 443 } 444 createMoreChip(); 445 } 446 447 private void expand() { 448 if (mShouldShrink) { 449 setMaxLines(Integer.MAX_VALUE); 450 } 451 removeMoreChip(); 452 setCursorVisible(true); 453 Editable text = getText(); 454 setSelection(text != null && text.length() > 0 ? text.length() : 0); 455 // If there are any temporary chips, try replacing them now that the user 456 // has expanded the field. 457 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) { 458 new RecipientReplacementTask().execute(); 459 mTemporaryRecipients = null; 460 } 461 } 462 463 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) { 464 paint.setTextSize(mChipFontSize); 465 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) { 466 Log.d(TAG, "Max width is negative: " + maxWidth); 467 } 468 return TextUtils.ellipsize(text, paint, maxWidth, 469 TextUtils.TruncateAt.END); 470 } 471 472 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 473 // Ellipsize the text so that it takes AT MOST the entire width of the 474 // autocomplete text entry area. Make sure to leave space for padding 475 // on the sides. 476 int height = (int) mChipHeight; 477 int deleteWidth = height; 478 float[] widths = new float[1]; 479 paint.getTextWidths(" ", widths); 480 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint, 481 calculateAvailableWidth(true) - deleteWidth - widths[0]); 482 483 // Make sure there is a minimum chip width so the user can ALWAYS 484 // tap a chip without difficulty. 485 int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 486 ellipsizedText.length())) 487 + (mChipPadding * 2) + deleteWidth); 488 489 // Create the background of the chip. 490 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 491 Canvas canvas = new Canvas(tmpBitmap); 492 if (mChipBackgroundPressed != null) { 493 mChipBackgroundPressed.setBounds(0, 0, width, height); 494 mChipBackgroundPressed.draw(canvas); 495 paint.setColor(sSelectedTextColor); 496 // Vertically center the text in the chip. 497 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 498 getTextYOffset((String) ellipsizedText, paint, height), paint); 499 // Make the delete a square. 500 Rect backgroundPadding = new Rect(); 501 mChipBackgroundPressed.getPadding(backgroundPadding); 502 mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left, 503 0 + backgroundPadding.top, 504 width - backgroundPadding.right, 505 height - backgroundPadding.bottom); 506 mChipDelete.draw(canvas); 507 } else { 508 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 509 } 510 return tmpBitmap; 511 } 512 513 514 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout, 515 boolean leaveBlankIconSpacer) { 516 // Ellipsize the text so that it takes AT MOST the entire width of the 517 // autocomplete text entry area. Make sure to leave space for padding 518 // on the sides. 519 int height = (int) mChipHeight; 520 int iconWidth = height; 521 float[] widths = new float[1]; 522 paint.getTextWidths(" ", widths); 523 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint, 524 calculateAvailableWidth(false) - iconWidth - widths[0]); 525 // Make sure there is a minimum chip width so the user can ALWAYS 526 // tap a chip without difficulty. 527 int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 528 ellipsizedText.length())) 529 + (mChipPadding * 2) + iconWidth); 530 531 // Create the background of the chip. 532 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 533 Canvas canvas = new Canvas(tmpBitmap); 534 Drawable background = getChipBackground(contact); 535 if (background != null) { 536 background.setBounds(0, 0, width, height); 537 background.draw(canvas); 538 539 // Don't draw photos for recipients that have been typed in OR generated on the fly. 540 long contactId = contact.getContactId(); 541 boolean drawPhotos = isPhoneQuery() ? 542 contactId != RecipientEntry.INVALID_CONTACT 543 : (contactId != RecipientEntry.INVALID_CONTACT 544 && (contactId != RecipientEntry.GENERATED_CONTACT && 545 !TextUtils.isEmpty(contact.getDisplayName()))); 546 if (drawPhotos) { 547 byte[] photoBytes = contact.getPhotoBytes(); 548 // There may not be a photo yet if anything but the first contact address 549 // was selected. 550 if (photoBytes == null && contact.getPhotoThumbnailUri() != null) { 551 // TODO: cache this in the recipient entry? 552 ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact 553 .getPhotoThumbnailUri()); 554 photoBytes = contact.getPhotoBytes(); 555 } 556 557 Bitmap photo; 558 if (photoBytes != null) { 559 photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); 560 } else { 561 // TODO: can the scaled down default photo be cached? 562 photo = mDefaultContactPhoto; 563 } 564 // Draw the photo on the left side. 565 if (photo != null) { 566 RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight()); 567 Rect backgroundPadding = new Rect(); 568 mChipBackground.getPadding(backgroundPadding); 569 RectF dst = new RectF(width - iconWidth + backgroundPadding.left, 570 0 + backgroundPadding.top, 571 width - backgroundPadding.right, 572 height - backgroundPadding.bottom); 573 Matrix matrix = new Matrix(); 574 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL); 575 canvas.drawBitmap(photo, matrix, paint); 576 } 577 } else if (!leaveBlankIconSpacer || isPhoneQuery()) { 578 iconWidth = 0; 579 } 580 paint.setColor(getContext().getResources().getColor(android.R.color.black)); 581 // Vertically center the text in the chip. 582 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 583 getTextYOffset((String)ellipsizedText, paint, height), paint); 584 } else { 585 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 586 } 587 return tmpBitmap; 588 } 589 590 /** 591 * Get the background drawable for a RecipientChip. 592 */ 593 // Visible for testing. 594 /*package*/ Drawable getChipBackground(RecipientEntry contact) { 595 return (mValidator != null && mValidator.isValid(contact.getDestination())) ? 596 mChipBackground : mInvalidChipBackground; 597 } 598 599 private float getTextYOffset(String text, TextPaint paint, int height) { 600 Rect bounds = new Rect(); 601 paint.getTextBounds(text, 0, text.length(), bounds); 602 int textHeight = bounds.bottom - bounds.top ; 603 return height - ((height - textHeight) / 2) - (int)paint.descent(); 604 } 605 606 private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed, 607 boolean leaveIconSpace) throws NullPointerException { 608 if (mChipBackground == null) { 609 throw new NullPointerException( 610 "Unable to render any chips as setChipDimensions was not called."); 611 } 612 Layout layout = getLayout(); 613 614 TextPaint paint = getPaint(); 615 float defaultSize = paint.getTextSize(); 616 int defaultColor = paint.getColor(); 617 618 Bitmap tmpBitmap; 619 if (pressed) { 620 tmpBitmap = createSelectedChip(contact, paint, layout); 621 622 } else { 623 tmpBitmap = createUnselectedChip(contact, paint, layout, leaveIconSpace); 624 } 625 626 // Pass the full text, un-ellipsized, to the chip. 627 Drawable result = new BitmapDrawable(getResources(), tmpBitmap); 628 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight()); 629 RecipientChip recipientChip = new RecipientChip(result, contact, offset); 630 // Return text to the original size. 631 paint.setTextSize(defaultSize); 632 paint.setColor(defaultColor); 633 return recipientChip; 634 } 635 636 /** 637 * Calculate the bottom of the line the chip will be located on using: 638 * 1) which line the chip appears on 639 * 2) the height of a chip 640 * 3) padding built into the edit text view 641 */ 642 private int calculateOffsetFromBottom(int line) { 643 // Line offsets start at zero. 644 int actualLine = getLineCount() - (line + 1); 645 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop()) 646 + getDropDownVerticalOffset(); 647 } 648 649 /** 650 * Get the max amount of space a chip can take up. The formula takes into 651 * account the width of the EditTextView, any view padding, and padding 652 * that will be added to the chip. 653 */ 654 private float calculateAvailableWidth(boolean pressed) { 655 return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2); 656 } 657 658 659 private void setChipDimensions(Context context, AttributeSet attrs) { 660 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0, 661 0); 662 Resources r = getContext().getResources(); 663 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground); 664 if (mChipBackground == null) { 665 mChipBackground = r.getDrawable(R.drawable.chip_background); 666 } 667 mChipBackgroundPressed = a 668 .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed); 669 if (mChipBackgroundPressed == null) { 670 mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected); 671 } 672 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete); 673 if (mChipDelete == null) { 674 mChipDelete = r.getDrawable(R.drawable.chip_delete); 675 } 676 mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1); 677 if (mChipPadding == -1) { 678 mChipPadding = (int) r.getDimension(R.dimen.chip_padding); 679 } 680 mAlternatesLayout = a.getResourceId(R.styleable.RecipientEditTextView_chipAlternatesLayout, 681 -1); 682 if (mAlternatesLayout == -1) { 683 mAlternatesLayout = R.layout.chips_alternate_item; 684 } 685 686 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture); 687 688 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null); 689 690 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1); 691 if (mChipHeight == -1) { 692 mChipHeight = r.getDimension(R.dimen.chip_height); 693 } 694 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1); 695 if (mChipFontSize == -1) { 696 mChipFontSize = r.getDimension(R.dimen.chip_text_size); 697 } 698 mInvalidChipBackground = a 699 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground); 700 if (mInvalidChipBackground == null) { 701 mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid); 702 } 703 mLineSpacingExtra = context.getResources().getDimension(R.dimen.line_spacing_extra); 704 a.recycle(); 705 } 706 707 // Visible for testing. 708 /* package */ void setMoreItem(TextView moreItem) { 709 mMoreItem = moreItem; 710 } 711 712 713 // Visible for testing. 714 /* package */ void setChipBackground(Drawable chipBackground) { 715 mChipBackground = chipBackground; 716 } 717 718 // Visible for testing. 719 /* package */ void setChipHeight(int height) { 720 mChipHeight = height; 721 } 722 723 /** 724 * Set whether to shrink the recipients field such that at most 725 * one line of recipients chips are shown when the field loses 726 * focus. By default, the number of displayed recipients will be 727 * limited and a "more" chip will be shown when focus is lost. 728 * @param shrink 729 */ 730 public void setOnFocusListShrinkRecipients(boolean shrink) { 731 mShouldShrink = shrink; 732 } 733 734 @Override 735 public void onSizeChanged(int width, int height, int oldw, int oldh) { 736 super.onSizeChanged(width, height, oldw, oldh); 737 if (width != 0 && height != 0) { 738 if (mPendingChipsCount > 0) { 739 postHandlePendingChips(); 740 } else { 741 checkChipWidths(); 742 } 743 } 744 // Try to find the scroll view parent, if it exists. 745 if (mScrollView == null && !mTriedGettingScrollView) { 746 ViewParent parent = getParent(); 747 while (parent != null && !(parent instanceof ScrollView)) { 748 parent = parent.getParent(); 749 } 750 if (parent != null) { 751 mScrollView = (ScrollView) parent; 752 } 753 mTriedGettingScrollView = true; 754 } 755 } 756 757 private void postHandlePendingChips() { 758 mHandler.removeCallbacks(mHandlePendingChips); 759 mHandler.post(mHandlePendingChips); 760 } 761 762 private void checkChipWidths() { 763 // Check the widths of the associated chips. 764 RecipientChip[] chips = getSortedRecipients(); 765 if (chips != null) { 766 Rect bounds; 767 for (RecipientChip chip : chips) { 768 bounds = chip.getDrawable().getBounds(); 769 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) { 770 // Need to redraw that chip. 771 replaceChip(chip, chip.getEntry()); 772 } 773 } 774 } 775 } 776 777 // Visible for testing. 778 /*package*/ void handlePendingChips() { 779 if (getViewWidth() <= 0) { 780 // The widget has not been sized yet. 781 // This will be called as a result of onSizeChanged 782 // at a later point. 783 return; 784 } 785 if (mPendingChipsCount <= 0) { 786 return; 787 } 788 789 synchronized (mPendingChips) { 790 Editable editable = getText(); 791 // Tokenize! 792 if (mPendingChipsCount <= MAX_CHIPS_PARSED) { 793 for (int i = 0; i < mPendingChips.size(); i++) { 794 String current = mPendingChips.get(i); 795 int tokenStart = editable.toString().indexOf(current); 796 int tokenEnd = tokenStart + current.length(); 797 if (tokenStart >= 0) { 798 // When we have a valid token, include it with the token 799 // to the left. 800 if (tokenEnd < editable.length() - 2 801 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { 802 tokenEnd++; 803 } 804 createReplacementChip(tokenStart, tokenEnd, editable); 805 } 806 mPendingChipsCount--; 807 } 808 sanitizeEnd(); 809 } else { 810 mNoChips = true; 811 } 812 813 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0 814 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { 815 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { 816 new RecipientReplacementTask().execute(); 817 mTemporaryRecipients = null; 818 } else { 819 // Create the "more" chip 820 mIndividualReplacements = new IndividualReplacementTask(); 821 mIndividualReplacements.execute(new ArrayList<RecipientChip>( 822 mTemporaryRecipients.subList(0, CHIP_LIMIT))); 823 if (mTemporaryRecipients.size() > CHIP_LIMIT) { 824 mTemporaryRecipients = new ArrayList<RecipientChip>( 825 mTemporaryRecipients.subList(CHIP_LIMIT, 826 mTemporaryRecipients.size())); 827 } else { 828 mTemporaryRecipients = null; 829 } 830 createMoreChip(); 831 } 832 } else { 833 // There are too many recipients to look up, so just fall back 834 // to showing addresses for all of them. 835 mTemporaryRecipients = null; 836 createMoreChip(); 837 } 838 mPendingChipsCount = 0; 839 mPendingChips.clear(); 840 } 841 } 842 843 // Visible for testing. 844 /*package*/ int getViewWidth() { 845 return getWidth(); 846 } 847 848 /** 849 * Remove any characters after the last valid chip. 850 */ 851 // Visible for testing. 852 /*package*/ void sanitizeEnd() { 853 // Don't sanitize while we are waiting for pending chips to complete. 854 if (mPendingChipsCount > 0) { 855 return; 856 } 857 // Find the last chip; eliminate any commit characters after it. 858 RecipientChip[] chips = getSortedRecipients(); 859 if (chips != null && chips.length > 0) { 860 int end; 861 ImageSpan lastSpan; 862 mMoreChip = getMoreChip(); 863 if (mMoreChip != null) { 864 lastSpan = mMoreChip; 865 } else { 866 lastSpan = getLastChip(); 867 } 868 end = getSpannable().getSpanEnd(lastSpan); 869 Editable editable = getText(); 870 int length = editable.length(); 871 if (length > end) { 872 // See what characters occur after that and eliminate them. 873 if (Log.isLoggable(TAG, Log.DEBUG)) { 874 Log.d(TAG, "There were extra characters after the last tokenizable entry." 875 + editable); 876 } 877 editable.delete(end + 1, length); 878 } 879 } 880 } 881 882 /** 883 * Create a chip that represents just the email address of a recipient. At some later 884 * point, this chip will be attached to a real contact entry, if one exists. 885 */ 886 private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { 887 if (alreadyHasChip(tokenStart, tokenEnd)) { 888 // There is already a chip present at this location. 889 // Don't recreate it. 890 return; 891 } 892 String token = editable.toString().substring(tokenStart, tokenEnd); 893 int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); 894 if (commitCharIndex == token.length() - 1) { 895 token = token.substring(0, token.length() - 1); 896 } 897 RecipientEntry entry = createTokenizedEntry(token); 898 if (entry != null) { 899 String destText = createAddressText(entry); 900 // Always leave a blank space at the end of a chip. 901 int textLength = destText.length() - 1; 902 SpannableString chipText = new SpannableString(destText); 903 int end = getSelectionEnd(); 904 int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0; 905 RecipientChip chip = null; 906 try { 907 if (!mNoChips) { 908 /* leave space for the contact icon if this is not just an email address */ 909 chip = constructChipSpan( 910 entry, 911 start, 912 false, 913 TextUtils.isEmpty(entry.getDisplayName()) 914 || TextUtils.equals(entry.getDisplayName(), 915 entry.getDestination())); 916 chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 917 } 918 } catch (NullPointerException e) { 919 Log.e(TAG, e.getMessage(), e); 920 } 921 editable.replace(tokenStart, tokenEnd, chipText); 922 // Add this chip to the list of entries "to replace" 923 if (chip != null) { 924 if (mTemporaryRecipients == null) { 925 mTemporaryRecipients = new ArrayList<RecipientChip>(); 926 } 927 chip.setOriginalText(chipText.toString()); 928 mTemporaryRecipients.add(chip); 929 } 930 } 931 } 932 933 private static boolean isPhoneNumber(String number) { 934 // TODO: replace this function with libphonenumber's isPossibleNumber (see 935 // PhoneNumberUtil). One complication is that it requires the sender's region which 936 // comes from the CurrentCountryIso. For now, let's just do this simple match. 937 if (TextUtils.isEmpty(number)) { 938 return false; 939 } 940 941 Matcher match = Patterns.PHONE.matcher(number); 942 return match.matches(); 943 } 944 945 private RecipientEntry createTokenizedEntry(String token) { 946 if (TextUtils.isEmpty(token)) { 947 return null; 948 } 949 if (isPhoneQuery() && isPhoneNumber(token)) { 950 return RecipientEntry 951 .constructFakeEntry(token); 952 } 953 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 954 String display = null; 955 if (isValid(token) && tokens != null && tokens.length > 0) { 956 // If we can get a name from tokenizing, then generate an entry from 957 // this. 958 display = tokens[0].getName(); 959 if (!TextUtils.isEmpty(display)) { 960 if (!isPhoneQuery()) { 961 if (!TextUtils.isEmpty(token)) { 962 token = token.trim(); 963 } 964 char charAt = token.charAt(token.length() - 1); 965 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 966 token = token.substring(0, token.length() - 1); 967 } 968 } 969 return RecipientEntry.constructGeneratedEntry(display, token); 970 } else { 971 display = tokens[0].getAddress(); 972 if (!TextUtils.isEmpty(display)) { 973 return RecipientEntry.constructFakeEntry(display); 974 } 975 } 976 } 977 // Unable to validate the token or to create a valid token from it. 978 // Just create a chip the user can edit. 979 String validatedToken = null; 980 if (mValidator != null && !mValidator.isValid(token)) { 981 // Try fixing up the entry using the validator. 982 validatedToken = mValidator.fixText(token).toString(); 983 if (!TextUtils.isEmpty(validatedToken)) { 984 if (validatedToken.contains(token)) { 985 // protect against the case of a validator with a null domain, 986 // which doesn't add a domain to the token 987 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 988 if (tokenized.length > 0) { 989 validatedToken = tokenized[0].getAddress(); 990 } 991 } else { 992 // We ran into a case where the token was invalid and removed 993 // by the validator. In this case, just use the original token 994 // and let the user sort out the error chip. 995 validatedToken = null; 996 } 997 } 998 } 999 // Otherwise, fallback to just creating an editable email address chip. 1000 return RecipientEntry 1001 .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token); 1002 } 1003 1004 private boolean isValid(String text) { 1005 return mValidator == null ? true : mValidator.isValid(text); 1006 } 1007 1008 private String tokenizeAddress(String destination) { 1009 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); 1010 if (tokens != null && tokens.length > 0) { 1011 return tokens[0].getAddress(); 1012 } 1013 return destination; 1014 } 1015 1016 @Override 1017 public void setTokenizer(Tokenizer tokenizer) { 1018 mTokenizer = tokenizer; 1019 super.setTokenizer(mTokenizer); 1020 } 1021 1022 @Override 1023 public void setValidator(Validator validator) { 1024 mValidator = validator; 1025 super.setValidator(validator); 1026 } 1027 1028 /** 1029 * We cannot use the default mechanism for replaceText. Instead, 1030 * we override onItemClickListener so we can get all the associated 1031 * contact information including display text, address, and id. 1032 */ 1033 @Override 1034 protected void replaceText(CharSequence text) { 1035 return; 1036 } 1037 1038 /** 1039 * Dismiss any selected chips when the back key is pressed. 1040 */ 1041 @Override 1042 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 1043 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) { 1044 clearSelectedChip(); 1045 return true; 1046 } 1047 return super.onKeyPreIme(keyCode, event); 1048 } 1049 1050 /** 1051 * Monitor key presses in this view to see if the user types 1052 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. 1053 * If the user has entered text that has contact matches and types 1054 * a commit key, create a chip from the topmost matching contact. 1055 * If the user has entered text that has no contact matches and types 1056 * a commit key, then create a chip from the text they have entered. 1057 */ 1058 @Override 1059 public boolean onKeyUp(int keyCode, KeyEvent event) { 1060 switch (keyCode) { 1061 case KeyEvent.KEYCODE_ENTER: 1062 case KeyEvent.KEYCODE_DPAD_CENTER: 1063 if (event.hasNoModifiers()) { 1064 if (commitDefault()) { 1065 return true; 1066 } 1067 if (mSelectedChip != null) { 1068 clearSelectedChip(); 1069 return true; 1070 } else if (focusNext()) { 1071 return true; 1072 } 1073 } 1074 break; 1075 case KeyEvent.KEYCODE_TAB: 1076 if (event.hasNoModifiers()) { 1077 if (mSelectedChip != null) { 1078 clearSelectedChip(); 1079 } else { 1080 commitDefault(); 1081 } 1082 if (focusNext()) { 1083 return true; 1084 } 1085 } 1086 break; 1087 } 1088 return super.onKeyUp(keyCode, event); 1089 } 1090 1091 private boolean focusNext() { 1092 View next = focusSearch(View.FOCUS_DOWN); 1093 if (next != null) { 1094 next.requestFocus(); 1095 return true; 1096 } 1097 return false; 1098 } 1099 1100 /** 1101 * Create a chip from the default selection. If the popup is showing, the 1102 * default is the first item in the popup suggestions list. Otherwise, it is 1103 * whatever the user had typed in. End represents where the the tokenizer 1104 * should search for a token to turn into a chip. 1105 * @return If a chip was created from a real contact. 1106 */ 1107 private boolean commitDefault() { 1108 // If there is no tokenizer, don't try to commit. 1109 if (mTokenizer == null) { 1110 return false; 1111 } 1112 Editable editable = getText(); 1113 int end = getSelectionEnd(); 1114 int start = mTokenizer.findTokenStart(editable, end); 1115 1116 if (shouldCreateChip(start, end)) { 1117 int whatEnd = mTokenizer.findTokenEnd(getText(), start); 1118 // In the middle of chip; treat this as an edit 1119 // and commit the whole token. 1120 whatEnd = movePastTerminators(whatEnd); 1121 if (whatEnd != getSelectionEnd()) { 1122 handleEdit(start, whatEnd); 1123 return true; 1124 } 1125 return commitChip(start, end , editable); 1126 } 1127 return false; 1128 } 1129 1130 private void commitByCharacter() { 1131 // We can't possibly commit by character if we can't tokenize. 1132 if (mTokenizer == null) { 1133 return; 1134 } 1135 Editable editable = getText(); 1136 int end = getSelectionEnd(); 1137 int start = mTokenizer.findTokenStart(editable, end); 1138 if (shouldCreateChip(start, end)) { 1139 commitChip(start, end, editable); 1140 } 1141 setSelection(getText().length()); 1142 } 1143 1144 private boolean commitChip(int start, int end, Editable editable) { 1145 ListAdapter adapter = getAdapter(); 1146 if (adapter != null && adapter.getCount() > 0 && enoughToFilter() 1147 && end == getSelectionEnd() && !isPhoneQuery()) { 1148 // choose the first entry. 1149 submitItemAtPosition(0); 1150 dismissDropDown(); 1151 return true; 1152 } else { 1153 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 1154 if (editable.length() > tokenEnd + 1) { 1155 char charAt = editable.charAt(tokenEnd + 1); 1156 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 1157 tokenEnd++; 1158 } 1159 } 1160 String text = editable.toString().substring(start, tokenEnd).trim(); 1161 clearComposingText(); 1162 if (text != null && text.length() > 0 && !text.equals(" ")) { 1163 RecipientEntry entry = createTokenizedEntry(text); 1164 if (entry != null) { 1165 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1166 CharSequence chipText = createChip(entry, false); 1167 if (chipText != null && start > -1 && end > -1) { 1168 editable.replace(start, end, chipText); 1169 } 1170 } 1171 // Only dismiss the dropdown if it is related to the text we 1172 // just committed. 1173 // For paste, it may not be as there are possibly multiple 1174 // tokens being added. 1175 if (end == getSelectionEnd()) { 1176 dismissDropDown(); 1177 } 1178 sanitizeBetween(); 1179 return true; 1180 } 1181 } 1182 return false; 1183 } 1184 1185 // Visible for testing. 1186 /* package */ void sanitizeBetween() { 1187 // Don't sanitize while we are waiting for content to chipify. 1188 if (mPendingChipsCount > 0) { 1189 return; 1190 } 1191 // Find the last chip. 1192 RecipientChip[] recips = getSortedRecipients(); 1193 if (recips != null && recips.length > 0) { 1194 RecipientChip last = recips[recips.length - 1]; 1195 RecipientChip beforeLast = null; 1196 if (recips.length > 1) { 1197 beforeLast = recips[recips.length - 2]; 1198 } 1199 int startLooking = 0; 1200 int end = getSpannable().getSpanStart(last); 1201 if (beforeLast != null) { 1202 startLooking = getSpannable().getSpanEnd(beforeLast); 1203 Editable text = getText(); 1204 if (startLooking == -1 || startLooking > text.length() - 1) { 1205 // There is nothing after this chip. 1206 return; 1207 } 1208 if (text.charAt(startLooking) == ' ') { 1209 startLooking++; 1210 } 1211 } 1212 if (startLooking >= 0 && end >= 0 && startLooking < end) { 1213 getText().delete(startLooking, end); 1214 } 1215 } 1216 } 1217 1218 private boolean shouldCreateChip(int start, int end) { 1219 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1220 } 1221 1222 private boolean alreadyHasChip(int start, int end) { 1223 if (mNoChips) { 1224 return true; 1225 } 1226 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 1227 if ((chips == null || chips.length == 0)) { 1228 return false; 1229 } 1230 return true; 1231 } 1232 1233 private void handleEdit(int start, int end) { 1234 if (start == -1 || end == -1) { 1235 // This chip no longer exists in the field. 1236 dismissDropDown(); 1237 return; 1238 } 1239 // This is in the middle of a chip, so select out the whole chip 1240 // and commit it. 1241 Editable editable = getText(); 1242 setSelection(end); 1243 String text = getText().toString().substring(start, end); 1244 if (!TextUtils.isEmpty(text)) { 1245 RecipientEntry entry = RecipientEntry.constructFakeEntry(text); 1246 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1247 CharSequence chipText = createChip(entry, false); 1248 int selEnd = getSelectionEnd(); 1249 if (chipText != null && start > -1 && selEnd > -1) { 1250 editable.replace(start, selEnd, chipText); 1251 } 1252 } 1253 dismissDropDown(); 1254 } 1255 1256 /** 1257 * If there is a selected chip, delegate the key events 1258 * to the selected chip. 1259 */ 1260 @Override 1261 public boolean onKeyDown(int keyCode, KeyEvent event) { 1262 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { 1263 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1264 mAlternatesPopup.dismiss(); 1265 } 1266 removeChip(mSelectedChip); 1267 } 1268 1269 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1270 return true; 1271 } 1272 1273 return super.onKeyDown(keyCode, event); 1274 } 1275 1276 // Visible for testing. 1277 /* package */ Spannable getSpannable() { 1278 return getText(); 1279 } 1280 1281 private int getChipStart(RecipientChip chip) { 1282 return getSpannable().getSpanStart(chip); 1283 } 1284 1285 private int getChipEnd(RecipientChip chip) { 1286 return getSpannable().getSpanEnd(chip); 1287 } 1288 1289 /** 1290 * Instead of filtering on the entire contents of the edit box, 1291 * this subclass method filters on the range from 1292 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1293 * if the length of that range meets or exceeds {@link #getThreshold} 1294 * and makes sure that the range is not already a Chip. 1295 */ 1296 @Override 1297 protected void performFiltering(CharSequence text, int keyCode) { 1298 if (enoughToFilter() && !isCompletedToken(text)) { 1299 int end = getSelectionEnd(); 1300 int start = mTokenizer.findTokenStart(text, end); 1301 // If this is a RecipientChip, don't filter 1302 // on its contents. 1303 Spannable span = getSpannable(); 1304 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1305 if (chips != null && chips.length > 0) { 1306 return; 1307 } 1308 } 1309 super.performFiltering(text, keyCode); 1310 } 1311 1312 // Visible for testing. 1313 /*package*/ boolean isCompletedToken(CharSequence text) { 1314 if (TextUtils.isEmpty(text)) { 1315 return false; 1316 } 1317 // Check to see if this is a completed token before filtering. 1318 int end = text.length(); 1319 int start = mTokenizer.findTokenStart(text, end); 1320 String token = text.toString().substring(start, end).trim(); 1321 if (!TextUtils.isEmpty(token)) { 1322 char atEnd = token.charAt(token.length() - 1); 1323 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON; 1324 } 1325 return false; 1326 } 1327 1328 private void clearSelectedChip() { 1329 if (mSelectedChip != null) { 1330 unselectChip(mSelectedChip); 1331 mSelectedChip = null; 1332 } 1333 setCursorVisible(true); 1334 } 1335 1336 /** 1337 * Monitor touch events in the RecipientEditTextView. 1338 * If the view does not have focus, any tap on the view 1339 * will just focus the view. If the view has focus, determine 1340 * if the touch target is a recipient chip. If it is and the chip 1341 * is not selected, select it and clear any other selected chips. 1342 * If it isn't, then select that chip. 1343 */ 1344 @Override 1345 public boolean onTouchEvent(MotionEvent event) { 1346 if (!isFocused()) { 1347 // Ignore any chip taps until this view is focused. 1348 return super.onTouchEvent(event); 1349 } 1350 boolean handled = super.onTouchEvent(event); 1351 int action = event.getAction(); 1352 boolean chipWasSelected = false; 1353 if (mSelectedChip == null) { 1354 mGestureDetector.onTouchEvent(event); 1355 } 1356 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1357 float x = event.getX(); 1358 float y = event.getY(); 1359 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1360 RecipientChip currentChip = findChip(offset); 1361 if (currentChip != null) { 1362 if (action == MotionEvent.ACTION_UP) { 1363 if (mSelectedChip != null && mSelectedChip != currentChip) { 1364 clearSelectedChip(); 1365 mSelectedChip = selectChip(currentChip); 1366 } else if (mSelectedChip == null) { 1367 setSelection(getText().length()); 1368 commitDefault(); 1369 mSelectedChip = selectChip(currentChip); 1370 } else { 1371 onClick(mSelectedChip, offset, x, y); 1372 } 1373 } 1374 chipWasSelected = true; 1375 handled = true; 1376 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) { 1377 chipWasSelected = true; 1378 } 1379 } 1380 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1381 clearSelectedChip(); 1382 } 1383 return handled; 1384 } 1385 1386 private void scrollLineIntoView(int line) { 1387 if (mScrollView != null) { 1388 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1389 } 1390 } 1391 1392 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1393 int width, Context context) { 1394 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1395 int bottom; 1396 if (line == getLineCount() -1) { 1397 bottom = 0; 1398 } else { 1399 bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1 1400 - line))); 1401 } 1402 // Align the alternates popup with the left side of the View, 1403 // regardless of the position of the chip tapped. 1404 alternatesPopup.setWidth(width); 1405 alternatesPopup.setAnchorView(this); 1406 alternatesPopup.setVerticalOffset(bottom); 1407 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1408 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1409 // Clear the checked item. 1410 mCheckedItem = -1; 1411 alternatesPopup.show(); 1412 ListView listView = alternatesPopup.getListView(); 1413 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1414 // Checked item would be -1 if the adapter has not 1415 // loaded the view that should be checked yet. The 1416 // variable will be set correctly when onCheckedItemChanged 1417 // is called in a separate thread. 1418 if (mCheckedItem != -1) { 1419 listView.setItemChecked(mCheckedItem, true); 1420 mCheckedItem = -1; 1421 } 1422 } 1423 1424 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1425 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1426 mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this); 1427 } 1428 1429 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1430 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1431 .getEntry()); 1432 } 1433 1434 @Override 1435 public void onCheckedItemChanged(int position) { 1436 ListView listView = mAlternatesPopup.getListView(); 1437 if (listView != null && listView.getCheckedItemCount() == 0) { 1438 listView.setItemChecked(position, true); 1439 } 1440 mCheckedItem = position; 1441 } 1442 1443 // TODO: This algorithm will need a lot of tweaking after more people have used 1444 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1445 // what comes before the finger. 1446 private int putOffsetInRange(int o) { 1447 int offset = o; 1448 Editable text = getText(); 1449 int length = text.length(); 1450 // Remove whitespace from end to find "real end" 1451 int realLength = length; 1452 for (int i = length - 1; i >= 0; i--) { 1453 if (text.charAt(i) == ' ') { 1454 realLength--; 1455 } else { 1456 break; 1457 } 1458 } 1459 1460 // If the offset is beyond or at the end of the text, 1461 // leave it alone. 1462 if (offset >= realLength) { 1463 return offset; 1464 } 1465 Editable editable = getText(); 1466 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1467 // Keep walking backward! 1468 offset--; 1469 } 1470 return offset; 1471 } 1472 1473 private int findText(Editable text, int offset) { 1474 if (text.charAt(offset) != ' ') { 1475 return offset; 1476 } 1477 return -1; 1478 } 1479 1480 private RecipientChip findChip(int offset) { 1481 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1482 // Find the chip that contains this offset. 1483 for (int i = 0; i < chips.length; i++) { 1484 RecipientChip chip = chips[i]; 1485 int start = getChipStart(chip); 1486 int end = getChipEnd(chip); 1487 if (offset >= start && offset <= end) { 1488 return chip; 1489 } 1490 } 1491 return null; 1492 } 1493 1494 // Visible for testing. 1495 // Use this method to generate text to add to the list of addresses. 1496 /* package */String createAddressText(RecipientEntry entry) { 1497 String display = entry.getDisplayName(); 1498 String address = entry.getDestination(); 1499 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1500 display = null; 1501 } 1502 String trimmedDisplayText; 1503 if (isPhoneQuery() && isPhoneNumber(address)) { 1504 trimmedDisplayText = address.trim(); 1505 } else { 1506 if (address != null) { 1507 // Tokenize out the address in case the address already 1508 // contained the username as well. 1509 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1510 if (tokenized != null && tokenized.length > 0) { 1511 address = tokenized[0].getAddress(); 1512 } 1513 } 1514 Rfc822Token token = new Rfc822Token(display, address, null); 1515 trimmedDisplayText = token.toString().trim(); 1516 } 1517 int index = trimmedDisplayText.indexOf(","); 1518 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText) 1519 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1520 .terminateToken(trimmedDisplayText) : trimmedDisplayText; 1521 } 1522 1523 // Visible for testing. 1524 // Use this method to generate text to display in a chip. 1525 /*package*/ String createChipDisplayText(RecipientEntry entry) { 1526 String display = entry.getDisplayName(); 1527 String address = entry.getDestination(); 1528 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1529 display = null; 1530 } 1531 if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) { 1532 // Tokenize out the address in case the address already 1533 // contained the username as well. 1534 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1535 if (tokenized != null && tokenized.length > 0) { 1536 address = tokenized[0].getAddress(); 1537 } 1538 } 1539 if (!TextUtils.isEmpty(display)) { 1540 return display; 1541 } else if (!TextUtils.isEmpty(address)){ 1542 return address; 1543 } else { 1544 return new Rfc822Token(display, address, null).toString(); 1545 } 1546 } 1547 1548 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1549 String displayText = createAddressText(entry); 1550 if (TextUtils.isEmpty(displayText)) { 1551 return null; 1552 } 1553 SpannableString chipText = null; 1554 // Always leave a blank space at the end of a chip. 1555 int end = getSelectionEnd(); 1556 int start = mTokenizer.findTokenStart(getText(), end); 1557 int textLength = displayText.length()-1; 1558 chipText = new SpannableString(displayText); 1559 if (!mNoChips) { 1560 try { 1561 RecipientChip chip = constructChipSpan(entry, start, pressed, 1562 false /* leave space for contact icon */); 1563 chipText.setSpan(chip, 0, textLength, 1564 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1565 chip.setOriginalText(chipText.toString()); 1566 } catch (NullPointerException e) { 1567 Log.e(TAG, e.getMessage(), e); 1568 return null; 1569 } 1570 } 1571 return chipText; 1572 } 1573 1574 /** 1575 * When an item in the suggestions list has been clicked, create a chip from the 1576 * contact information of the selected item. 1577 */ 1578 @Override 1579 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1580 submitItemAtPosition(position); 1581 } 1582 1583 private void submitItemAtPosition(int position) { 1584 RecipientEntry entry = createValidatedEntry( 1585 (RecipientEntry)getAdapter().getItem(position)); 1586 if (entry == null) { 1587 return; 1588 } 1589 clearComposingText(); 1590 1591 int end = getSelectionEnd(); 1592 int start = mTokenizer.findTokenStart(getText(), end); 1593 1594 Editable editable = getText(); 1595 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1596 CharSequence chip = createChip(entry, false); 1597 if (chip != null && start >= 0 && end >= 0) { 1598 editable.replace(start, end, chip); 1599 } 1600 sanitizeBetween(); 1601 } 1602 1603 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1604 if (item == null) { 1605 return null; 1606 } 1607 final RecipientEntry entry; 1608 // If the display name and the address are the same, or if this is a 1609 // valid contact, but the destination is invalid, then make this a fake 1610 // recipient that is editable. 1611 String destination = item.getDestination(); 1612 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1613 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(), 1614 destination); 1615 } else if (RecipientEntry.isCreatedRecipient(item.getContactId()) 1616 && (TextUtils.isEmpty(item.getDisplayName()) 1617 || TextUtils.equals(item.getDisplayName(), destination) 1618 || (mValidator != null && !mValidator.isValid(destination)))) { 1619 entry = RecipientEntry.constructFakeEntry(destination); 1620 } else { 1621 entry = item; 1622 } 1623 return entry; 1624 } 1625 1626 /** Returns a collection of contact Id for each chip inside this View. */ 1627 /* package */ Collection<Long> getContactIds() { 1628 final Set<Long> result = new HashSet<Long>(); 1629 RecipientChip[] chips = getSortedRecipients(); 1630 if (chips != null) { 1631 for (RecipientChip chip : chips) { 1632 result.add(chip.getContactId()); 1633 } 1634 } 1635 return result; 1636 } 1637 1638 1639 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1640 /* package */ Collection<Long> getDataIds() { 1641 final Set<Long> result = new HashSet<Long>(); 1642 RecipientChip [] chips = getSortedRecipients(); 1643 if (chips != null) { 1644 for (RecipientChip chip : chips) { 1645 result.add(chip.getDataId()); 1646 } 1647 } 1648 return result; 1649 } 1650 1651 // Visible for testing. 1652 /* package */RecipientChip[] getSortedRecipients() { 1653 RecipientChip[] recips = getSpannable() 1654 .getSpans(0, getText().length(), RecipientChip.class); 1655 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1656 .asList(recips)); 1657 final Spannable spannable = getSpannable(); 1658 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1659 1660 @Override 1661 public int compare(RecipientChip first, RecipientChip second) { 1662 int firstStart = spannable.getSpanStart(first); 1663 int secondStart = spannable.getSpanStart(second); 1664 if (firstStart < secondStart) { 1665 return -1; 1666 } else if (firstStart > secondStart) { 1667 return 1; 1668 } else { 1669 return 0; 1670 } 1671 } 1672 }); 1673 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1674 } 1675 1676 @Override 1677 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1678 return false; 1679 } 1680 1681 @Override 1682 public void onDestroyActionMode(ActionMode mode) { 1683 } 1684 1685 @Override 1686 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1687 return false; 1688 } 1689 1690 /** 1691 * No chips are selectable. 1692 */ 1693 @Override 1694 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1695 return false; 1696 } 1697 1698 // Visible for testing. 1699 /* package */ImageSpan getMoreChip() { 1700 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1701 MoreImageSpan.class); 1702 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1703 } 1704 1705 private MoreImageSpan createMoreSpan(int count) { 1706 String moreText = String.format(mMoreItem.getText().toString(), count); 1707 TextPaint morePaint = new TextPaint(getPaint()); 1708 morePaint.setTextSize(mMoreItem.getTextSize()); 1709 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1710 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1711 + mMoreItem.getPaddingRight(); 1712 int height = getLineHeight(); 1713 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1714 Canvas canvas = new Canvas(drawable); 1715 int adjustedHeight = height; 1716 Layout layout = getLayout(); 1717 if (layout != null) { 1718 adjustedHeight -= layout.getLineDescent(0); 1719 } 1720 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1721 1722 Drawable result = new BitmapDrawable(getResources(), drawable); 1723 result.setBounds(0, 0, width, height); 1724 return new MoreImageSpan(result); 1725 } 1726 1727 // Visible for testing. 1728 /*package*/ void createMoreChipPlainText() { 1729 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one. 1730 Editable text = getText(); 1731 int start = 0; 1732 int end = start; 1733 for (int i = 0; i < CHIP_LIMIT; i++) { 1734 end = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1735 start = end; // move to the next token and get its end. 1736 } 1737 // Now, count total addresses. 1738 start = 0; 1739 int tokenCount = countTokens(text); 1740 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT); 1741 SpannableString chipText = new SpannableString(text.subSequence(end, text.length())); 1742 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1743 text.replace(end, text.length(), chipText); 1744 mMoreChip = moreSpan; 1745 } 1746 1747 // Visible for testing. 1748 /* package */int countTokens(Editable text) { 1749 int tokenCount = 0; 1750 int start = 0; 1751 while (start < text.length()) { 1752 start = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1753 tokenCount++; 1754 if (start >= text.length()) { 1755 break; 1756 } 1757 } 1758 return tokenCount; 1759 } 1760 1761 /** 1762 * Create the more chip. The more chip is text that replaces any chips that 1763 * do not fit in the pre-defined available space when the 1764 * RecipientEditTextView loses focus. 1765 */ 1766 // Visible for testing. 1767 /* package */ void createMoreChip() { 1768 if (mNoChips) { 1769 createMoreChipPlainText(); 1770 return; 1771 } 1772 1773 if (!mShouldShrink) { 1774 return; 1775 } 1776 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1777 if (tempMore.length > 0) { 1778 getSpannable().removeSpan(tempMore[0]); 1779 } 1780 RecipientChip[] recipients = getSortedRecipients(); 1781 1782 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1783 mMoreChip = null; 1784 return; 1785 } 1786 Spannable spannable = getSpannable(); 1787 int numRecipients = recipients.length; 1788 int overage = numRecipients - CHIP_LIMIT; 1789 MoreImageSpan moreSpan = createMoreSpan(overage); 1790 mRemovedSpans = new ArrayList<RecipientChip>(); 1791 int totalReplaceStart = 0; 1792 int totalReplaceEnd = 0; 1793 Editable text = getText(); 1794 for (int i = numRecipients - overage; i < recipients.length; i++) { 1795 mRemovedSpans.add(recipients[i]); 1796 if (i == numRecipients - overage) { 1797 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1798 } 1799 if (i == recipients.length - 1) { 1800 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1801 } 1802 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1803 int spanStart = spannable.getSpanStart(recipients[i]); 1804 int spanEnd = spannable.getSpanEnd(recipients[i]); 1805 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1806 } 1807 spannable.removeSpan(recipients[i]); 1808 } 1809 if (totalReplaceEnd < text.length()) { 1810 totalReplaceEnd = text.length(); 1811 } 1812 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1813 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1814 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1815 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1816 text.replace(start, end, chipText); 1817 mMoreChip = moreSpan; 1818 // If adding the +more chip goes over the limit, resize accordingly. 1819 if (!isPhoneQuery() && getLineCount() > mMaxLines) { 1820 setMaxLines(getLineCount()); 1821 } 1822 } 1823 1824 /** 1825 * Replace the more chip, if it exists, with all of the recipient chips it had 1826 * replaced when the RecipientEditTextView gains focus. 1827 */ 1828 // Visible for testing. 1829 /*package*/ void removeMoreChip() { 1830 if (mMoreChip != null) { 1831 Spannable span = getSpannable(); 1832 span.removeSpan(mMoreChip); 1833 mMoreChip = null; 1834 // Re-add the spans that were removed. 1835 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1836 // Recreate each removed span. 1837 RecipientChip[] recipients = getSortedRecipients(); 1838 // Start the search for tokens after the last currently visible 1839 // chip. 1840 if (recipients == null || recipients.length == 0) { 1841 return; 1842 } 1843 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1844 Editable editable = getText(); 1845 for (RecipientChip chip : mRemovedSpans) { 1846 int chipStart; 1847 int chipEnd; 1848 String token; 1849 // Need to find the location of the chip, again. 1850 token = (String) chip.getOriginalText(); 1851 // As we find the matching recipient for the remove spans, 1852 // reduce the size of the string we need to search. 1853 // That way, if there are duplicates, we always find the correct 1854 // recipient. 1855 chipStart = editable.toString().indexOf(token, end); 1856 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1857 // Only set the span if we found a matching token. 1858 if (chipStart != -1) { 1859 editable.setSpan(chip, chipStart, chipEnd, 1860 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1861 } 1862 } 1863 mRemovedSpans.clear(); 1864 } 1865 } 1866 } 1867 1868 /** 1869 * Show specified chip as selected. If the RecipientChip is just an email address, 1870 * selecting the chip will take the contents of the chip and place it at 1871 * the end of the RecipientEditTextView for inline editing. If the 1872 * RecipientChip is a complete contact, then selecting the chip 1873 * will change the background color of the chip, show the delete icon, 1874 * and a popup window with the address in use highlighted and any other 1875 * alternate addresses for the contact. 1876 * @param currentChip Chip to select. 1877 * @return A RecipientChip in the selected state or null if the chip 1878 * just contained an email address. 1879 */ 1880 private RecipientChip selectChip(RecipientChip currentChip) { 1881 if (shouldShowEditableText(currentChip)) { 1882 CharSequence text = currentChip.getValue(); 1883 Editable editable = getText(); 1884 getSpannable().removeSpan(currentChip); 1885 setCursorVisible(true); 1886 setSelection(editable.length()); 1887 return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1); 1888 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1889 int start = getChipStart(currentChip); 1890 int end = getChipEnd(currentChip); 1891 getSpannable().removeSpan(currentChip); 1892 RecipientChip newChip; 1893 try { 1894 if (mNoChips) { 1895 return null; 1896 } 1897 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1898 } catch (NullPointerException e) { 1899 Log.e(TAG, e.getMessage(), e); 1900 return null; 1901 } 1902 Editable editable = getText(); 1903 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1904 if (start == -1 || end == -1) { 1905 Log.d(TAG, "The chip being selected no longer exists but should."); 1906 } else { 1907 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1908 } 1909 newChip.setSelected(true); 1910 if (shouldShowEditableText(newChip)) { 1911 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1912 } 1913 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1914 setCursorVisible(false); 1915 return newChip; 1916 } else { 1917 int start = getChipStart(currentChip); 1918 int end = getChipEnd(currentChip); 1919 getSpannable().removeSpan(currentChip); 1920 RecipientChip newChip; 1921 try { 1922 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1923 } catch (NullPointerException e) { 1924 Log.e(TAG, e.getMessage(), e); 1925 return null; 1926 } 1927 Editable editable = getText(); 1928 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1929 if (start == -1 || end == -1) { 1930 Log.d(TAG, "The chip being selected no longer exists but should."); 1931 } else { 1932 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1933 } 1934 newChip.setSelected(true); 1935 if (shouldShowEditableText(newChip)) { 1936 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1937 } 1938 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1939 setCursorVisible(false); 1940 return newChip; 1941 } 1942 } 1943 1944 private boolean shouldShowEditableText(RecipientChip currentChip) { 1945 long contactId = currentChip.getContactId(); 1946 return contactId == RecipientEntry.INVALID_CONTACT 1947 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT); 1948 } 1949 1950 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1951 int width, Context context) { 1952 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1953 int bottom = calculateOffsetFromBottom(line); 1954 // Align the alternates popup with the left side of the View, 1955 // regardless of the position of the chip tapped. 1956 popup.setWidth(width); 1957 popup.setAnchorView(this); 1958 popup.setVerticalOffset(bottom); 1959 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1960 popup.setOnItemClickListener(new OnItemClickListener() { 1961 @Override 1962 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1963 unselectChip(currentChip); 1964 popup.dismiss(); 1965 } 1966 }); 1967 popup.show(); 1968 ListView listView = popup.getListView(); 1969 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1970 listView.setItemChecked(0, true); 1971 } 1972 1973 /** 1974 * Remove selection from this chip. Unselecting a RecipientChip will render 1975 * the chip without a delete icon and with an unfocused background. This is 1976 * called when the RecipientChip no longer has focus. 1977 */ 1978 private void unselectChip(RecipientChip chip) { 1979 int start = getChipStart(chip); 1980 int end = getChipEnd(chip); 1981 Editable editable = getText(); 1982 mSelectedChip = null; 1983 if (start == -1 || end == -1) { 1984 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing"); 1985 setSelection(editable.length()); 1986 commitDefault(); 1987 } else { 1988 getSpannable().removeSpan(chip); 1989 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1990 editable.removeSpan(chip); 1991 try { 1992 if (!mNoChips) { 1993 editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false), 1994 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1995 } 1996 } catch (NullPointerException e) { 1997 Log.e(TAG, e.getMessage(), e); 1998 } 1999 } 2000 setCursorVisible(true); 2001 setSelection(editable.length()); 2002 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 2003 mAlternatesPopup.dismiss(); 2004 } 2005 } 2006 2007 /** 2008 * Return whether a touch event was inside the delete target of 2009 * a selected chip. It is in the delete target if: 2010 * 1) the x and y points of the event are within the 2011 * delete assset. 2012 * 2) the point tapped would have caused a cursor to appear 2013 * right after the selected chip. 2014 * @return boolean 2015 */ 2016 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 2017 // Figure out the bounds of this chip and whether or not 2018 // the user clicked in the X portion. 2019 return chip.isSelected() && offset == getChipEnd(chip); 2020 } 2021 2022 /** 2023 * Remove the chip and any text associated with it from the RecipientEditTextView. 2024 */ 2025 // Visible for testing. 2026 /*pacakge*/ void removeChip(RecipientChip chip) { 2027 Spannable spannable = getSpannable(); 2028 int spanStart = spannable.getSpanStart(chip); 2029 int spanEnd = spannable.getSpanEnd(chip); 2030 Editable text = getText(); 2031 int toDelete = spanEnd; 2032 boolean wasSelected = chip == mSelectedChip; 2033 // Clear that there is a selected chip before updating any text. 2034 if (wasSelected) { 2035 mSelectedChip = null; 2036 } 2037 // Always remove trailing spaces when removing a chip. 2038 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') { 2039 toDelete++; 2040 } 2041 spannable.removeSpan(chip); 2042 if (spanStart >= 0 && toDelete > 0) { 2043 text.delete(spanStart, toDelete); 2044 } 2045 if (wasSelected) { 2046 clearSelectedChip(); 2047 } 2048 } 2049 2050 /** 2051 * Replace this currently selected chip with a new chip 2052 * that uses the contact data provided. 2053 */ 2054 // Visible for testing. 2055 /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) { 2056 boolean wasSelected = chip == mSelectedChip; 2057 if (wasSelected) { 2058 mSelectedChip = null; 2059 } 2060 int start = getChipStart(chip); 2061 int end = getChipEnd(chip); 2062 getSpannable().removeSpan(chip); 2063 Editable editable = getText(); 2064 CharSequence chipText = createChip(entry, false); 2065 if (chipText != null) { 2066 if (start == -1 || end == -1) { 2067 Log.e(TAG, "The chip to replace does not exist but should."); 2068 editable.insert(0, chipText); 2069 } else { 2070 if (!TextUtils.isEmpty(chipText)) { 2071 // There may be a space to replace with this chip's new 2072 // associated space. Check for it 2073 int toReplace = end; 2074 while (toReplace >= 0 && toReplace < editable.length() 2075 && editable.charAt(toReplace) == ' ') { 2076 toReplace++; 2077 } 2078 editable.replace(start, toReplace, chipText); 2079 } 2080 } 2081 } 2082 setCursorVisible(true); 2083 if (wasSelected) { 2084 clearSelectedChip(); 2085 } 2086 } 2087 2088 /** 2089 * Handle click events for a chip. When a selected chip receives a click 2090 * event, see if that event was in the delete icon. If so, delete it. 2091 * Otherwise, unselect the chip. 2092 */ 2093 public void onClick(RecipientChip chip, int offset, float x, float y) { 2094 if (chip.isSelected()) { 2095 if (isInDelete(chip, offset, x, y)) { 2096 removeChip(chip); 2097 } else { 2098 clearSelectedChip(); 2099 } 2100 } 2101 } 2102 2103 private boolean chipsPending() { 2104 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 2105 } 2106 2107 @Override 2108 public void removeTextChangedListener(TextWatcher watcher) { 2109 mTextWatcher = null; 2110 super.removeTextChangedListener(watcher); 2111 } 2112 2113 private class RecipientTextWatcher implements TextWatcher { 2114 2115 @Override 2116 public void afterTextChanged(Editable s) { 2117 // If the text has been set to null or empty, make sure we remove 2118 // all the spans we applied. 2119 if (TextUtils.isEmpty(s)) { 2120 // Remove all the chips spans. 2121 Spannable spannable = getSpannable(); 2122 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 2123 RecipientChip.class); 2124 for (RecipientChip chip : chips) { 2125 spannable.removeSpan(chip); 2126 } 2127 if (mMoreChip != null) { 2128 spannable.removeSpan(mMoreChip); 2129 } 2130 return; 2131 } 2132 // Get whether there are any recipients pending addition to the 2133 // view. If there are, don't do anything in the text watcher. 2134 if (chipsPending()) { 2135 return; 2136 } 2137 // If the user is editing a chip, don't clear it. 2138 if (mSelectedChip != null 2139 && shouldShowEditableText(mSelectedChip)) { 2140 setCursorVisible(true); 2141 setSelection(getText().length()); 2142 clearSelectedChip(); 2143 } 2144 int length = s.length(); 2145 // Make sure there is content there to parse and that it is 2146 // not just the commit character. 2147 if (length > 1) { 2148 char last; 2149 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 2150 int len = length() - 1; 2151 if (end != len) { 2152 last = s.charAt(end); 2153 } else { 2154 last = s.charAt(len); 2155 } 2156 if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { 2157 commitByCharacter(); 2158 } else if (last == COMMIT_CHAR_SPACE) { 2159 if (!isPhoneQuery()) { 2160 // Check if this is a valid email address. If it is, 2161 // commit it. 2162 String text = getText().toString(); 2163 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2164 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 2165 tokenStart)); 2166 if (!TextUtils.isEmpty(sub) && mValidator != null && 2167 mValidator.isValid(sub)) { 2168 commitByCharacter(); 2169 } 2170 } 2171 } 2172 } 2173 } 2174 2175 @Override 2176 public void onTextChanged(CharSequence s, int start, int before, int count) { 2177 // This is a delete; check to see if the insertion point is on a space 2178 // following a chip. 2179 if (before > count) { 2180 // If the item deleted is a space, and the thing before the 2181 // space is a chip, delete the entire span. 2182 int selStart = getSelectionStart(); 2183 RecipientChip[] repl = getSpannable().getSpans(selStart, selStart, 2184 RecipientChip.class); 2185 if (repl.length > 0) { 2186 // There is a chip there! Just remove it. 2187 Editable editable = getText(); 2188 // Add the separator token. 2189 int tokenStart = mTokenizer.findTokenStart(editable, selStart); 2190 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart); 2191 tokenEnd = tokenEnd + 1; 2192 if (tokenEnd > editable.length()) { 2193 tokenEnd = editable.length(); 2194 } 2195 editable.delete(tokenStart, tokenEnd); 2196 getSpannable().removeSpan(repl[0]); 2197 } 2198 } else if (count > before) { 2199 scrollBottomIntoView(); 2200 } 2201 } 2202 2203 @Override 2204 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 2205 // Do nothing. 2206 } 2207 } 2208 2209 private void scrollBottomIntoView() { 2210 if (mScrollView != null) { 2211 mScrollView.scrollBy(0, (int) (getLineCount() * mChipHeight)); 2212 } 2213 } 2214 2215 /** 2216 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}. 2217 */ 2218 private void handlePasteClip(ClipData clip) { 2219 removeTextChangedListener(mTextWatcher); 2220 2221 if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ 2222 for (int i = 0; i < clip.getItemCount(); i++) { 2223 CharSequence paste = clip.getItemAt(i).getText(); 2224 if (paste != null) { 2225 int start = getSelectionStart(); 2226 int end = getSelectionEnd(); 2227 Editable editable = getText(); 2228 if (start >= 0 && end >= 0 && start != end) { 2229 editable.append(paste, start, end); 2230 } else { 2231 editable.insert(end, paste); 2232 } 2233 handlePasteAndReplace(); 2234 } 2235 } 2236 } 2237 2238 mHandler.post(mAddTextWatcher); 2239 } 2240 2241 @Override 2242 public boolean onTextContextMenuItem(int id) { 2243 if (id == android.R.id.paste) { 2244 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2245 Context.CLIPBOARD_SERVICE); 2246 handlePasteClip(clipboard.getPrimaryClip()); 2247 return true; 2248 } 2249 return super.onTextContextMenuItem(id); 2250 } 2251 2252 private void handlePasteAndReplace() { 2253 ArrayList<RecipientChip> created = handlePaste(); 2254 if (created != null && created.size() > 0) { 2255 // Perform reverse lookups on the pasted contacts. 2256 IndividualReplacementTask replace = new IndividualReplacementTask(); 2257 replace.execute(created); 2258 } 2259 } 2260 2261 // Visible for testing. 2262 /* package */ArrayList<RecipientChip> handlePaste() { 2263 String text = getText().toString(); 2264 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2265 String lastAddress = text.substring(originalTokenStart); 2266 int tokenStart = originalTokenStart; 2267 int prevTokenStart = tokenStart; 2268 RecipientChip findChip = null; 2269 ArrayList<RecipientChip> created = new ArrayList<RecipientChip>(); 2270 if (tokenStart != 0) { 2271 // There are things before this! 2272 while (tokenStart != 0 && findChip == null) { 2273 prevTokenStart = tokenStart; 2274 tokenStart = mTokenizer.findTokenStart(text, tokenStart); 2275 findChip = findChip(tokenStart); 2276 } 2277 if (tokenStart != originalTokenStart) { 2278 if (findChip != null) { 2279 tokenStart = prevTokenStart; 2280 } 2281 int tokenEnd; 2282 RecipientChip createdChip; 2283 while (tokenStart < originalTokenStart) { 2284 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(), 2285 tokenStart)); 2286 commitChip(tokenStart, tokenEnd, getText()); 2287 createdChip = findChip(tokenStart); 2288 if (createdChip == null) { 2289 break; 2290 } 2291 // +1 for the space at the end. 2292 tokenStart = getSpannable().getSpanEnd(createdChip) + 1; 2293 created.add(createdChip); 2294 } 2295 } 2296 } 2297 // Take a look at the last token. If the token has been completed with a 2298 // commit character, create a chip. 2299 if (isCompletedToken(lastAddress)) { 2300 Editable editable = getText(); 2301 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart); 2302 commitChip(tokenStart, editable.length(), editable); 2303 created.add(findChip(tokenStart)); 2304 } 2305 return created; 2306 } 2307 2308 // Visible for testing. 2309 /* package */int movePastTerminators(int tokenEnd) { 2310 if (tokenEnd >= length()) { 2311 return tokenEnd; 2312 } 2313 char atEnd = getText().toString().charAt(tokenEnd); 2314 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) { 2315 tokenEnd++; 2316 } 2317 // This token had not only an end token character, but also a space 2318 // separating it from the next token. 2319 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') { 2320 tokenEnd++; 2321 } 2322 return tokenEnd; 2323 } 2324 2325 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 2326 private RecipientChip createFreeChip(RecipientEntry entry) { 2327 try { 2328 if (mNoChips) { 2329 return null; 2330 } 2331 return constructChipSpan(entry, -1, false, 2332 false /*leave space for contact icon */); 2333 } catch (NullPointerException e) { 2334 Log.e(TAG, e.getMessage(), e); 2335 return null; 2336 } 2337 } 2338 2339 @Override 2340 protected Void doInBackground(Void... params) { 2341 if (mIndividualReplacements != null) { 2342 mIndividualReplacements.cancel(true); 2343 } 2344 // For each chip in the list, look up the matching contact. 2345 // If there is a match, replace that chip with the matching 2346 // chip. 2347 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 2348 RecipientChip[] existingChips = getSortedRecipients(); 2349 for (int i = 0; i < existingChips.length; i++) { 2350 originalRecipients.add(existingChips[i]); 2351 } 2352 if (mRemovedSpans != null) { 2353 originalRecipients.addAll(mRemovedSpans); 2354 } 2355 ArrayList<String> addresses = new ArrayList<String>(); 2356 RecipientChip chip; 2357 for (int i = 0; i < originalRecipients.size(); i++) { 2358 chip = originalRecipients.get(i); 2359 if (chip != null) { 2360 addresses.add(createAddressText(chip.getEntry())); 2361 } 2362 } 2363 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2364 .getMatchingRecipients(getContext(), addresses); 2365 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 2366 for (final RecipientChip temp : originalRecipients) { 2367 RecipientEntry entry = null; 2368 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2369 && getSpannable().getSpanStart(temp) != -1) { 2370 // Replace this. 2371 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 2372 .getDestination()))); 2373 } 2374 if (entry != null) { 2375 replacements.add(createFreeChip(entry)); 2376 } else { 2377 replacements.add(temp); 2378 } 2379 } 2380 if (replacements != null && replacements.size() > 0) { 2381 mHandler.post(new Runnable() { 2382 @Override 2383 public void run() { 2384 Editable oldText = getText(); 2385 int start, end; 2386 int i = 0; 2387 for (RecipientChip chip : originalRecipients) { 2388 // Find the location of the chip in the text currently shown. 2389 start = oldText.getSpanStart(chip); 2390 if (start != -1) { 2391 end = oldText.getSpanEnd(chip); 2392 oldText.removeSpan(chip); 2393 RecipientChip replacement = replacements.get(i); 2394 // Trim any whitespace, as we will already have 2395 // it added if these are replacement chips. 2396 SpannableString displayText = new SpannableString( 2397 createAddressText(replacement.getEntry()).trim()); 2398 displayText.setSpan(replacement, 0, displayText.length(), 2399 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2400 // Replace the old text we found with with the new display text, 2401 // which now may also contain the display name of the recipient. 2402 oldText.replace(start, end, displayText); 2403 replacement.setOriginalText(displayText.toString()); 2404 } 2405 i++; 2406 } 2407 originalRecipients.clear(); 2408 } 2409 }); 2410 } 2411 return null; 2412 } 2413 } 2414 2415 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 2416 @SuppressWarnings("unchecked") 2417 @Override 2418 protected Void doInBackground(Object... params) { 2419 // For each chip in the list, look up the matching contact. 2420 // If there is a match, replace that chip with the matching 2421 // chip. 2422 final ArrayList<RecipientChip> originalRecipients = 2423 (ArrayList<RecipientChip>) params[0]; 2424 ArrayList<String> addresses = new ArrayList<String>(); 2425 RecipientChip chip; 2426 for (int i = 0; i < originalRecipients.size(); i++) { 2427 chip = originalRecipients.get(i); 2428 if (chip != null) { 2429 addresses.add(createAddressText(chip.getEntry())); 2430 } 2431 } 2432 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2433 .getMatchingRecipients(getContext(), addresses); 2434 for (final RecipientChip temp : originalRecipients) { 2435 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2436 && getSpannable().getSpanStart(temp) != -1) { 2437 // Replace this. 2438 RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress( 2439 temp.getEntry().getDestination()).toLowerCase())); 2440 // If we don't have a validated contact match, just use the 2441 // entry as it existed before. 2442 if (entry == null && !isPhoneQuery()) { 2443 entry = temp.getEntry(); 2444 } 2445 final RecipientEntry tempEntry = entry; 2446 if (tempEntry != null) { 2447 mHandler.post(new Runnable() { 2448 @Override 2449 public void run() { 2450 replaceChip(temp, tempEntry); 2451 } 2452 }); 2453 } 2454 } 2455 } 2456 return null; 2457 } 2458 } 2459 2460 2461 /** 2462 * MoreImageSpan is a simple class created for tracking the existence of a 2463 * more chip across activity restarts/ 2464 */ 2465 private class MoreImageSpan extends ImageSpan { 2466 public MoreImageSpan(Drawable b) { 2467 super(b); 2468 } 2469 } 2470 2471 @Override 2472 public boolean onDown(MotionEvent e) { 2473 return false; 2474 } 2475 2476 @Override 2477 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2478 // Do nothing. 2479 return false; 2480 } 2481 2482 @Override 2483 public void onLongPress(MotionEvent event) { 2484 if (mSelectedChip != null) { 2485 return; 2486 } 2487 float x = event.getX(); 2488 float y = event.getY(); 2489 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2490 RecipientChip currentChip = findChip(offset); 2491 if (currentChip != null) { 2492 if (mDragEnabled) { 2493 // Start drag-and-drop for the selected chip. 2494 startDrag(currentChip); 2495 } else { 2496 // Copy the selected chip email address. 2497 showCopyDialog(currentChip.getEntry().getDestination()); 2498 } 2499 } 2500 } 2501 2502 /** 2503 * Enables drag-and-drop for chips. 2504 */ 2505 public void enableDrag() { 2506 mDragEnabled = true; 2507 } 2508 2509 /** 2510 * Starts drag-and-drop for the selected chip. 2511 */ 2512 private void startDrag(RecipientChip currentChip) { 2513 String address = currentChip.getEntry().getDestination(); 2514 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA); 2515 2516 // Start drag mode. 2517 startDrag(data, new RecipientChipShadow(currentChip), null, 0); 2518 2519 // Remove the current chip, so drag-and-drop will result in a move. 2520 // TODO (phamm): consider readd this chip if it's dropped outside a target. 2521 removeChip(currentChip); 2522 } 2523 2524 /** 2525 * Handles drag event. 2526 */ 2527 @Override 2528 public boolean onDragEvent(DragEvent event) { 2529 switch (event.getAction()) { 2530 case DragEvent.ACTION_DRAG_STARTED: 2531 // Only handle plain text drag and drop. 2532 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); 2533 case DragEvent.ACTION_DRAG_ENTERED: 2534 requestFocus(); 2535 return true; 2536 case DragEvent.ACTION_DROP: 2537 handlePasteClip(event.getClipData()); 2538 return true; 2539 } 2540 return false; 2541 } 2542 2543 /** 2544 * Drag shadow for a {@link RecipientChip}. 2545 */ 2546 private final class RecipientChipShadow extends DragShadowBuilder { 2547 private final RecipientChip mChip; 2548 2549 public RecipientChipShadow(RecipientChip chip) { 2550 mChip = chip; 2551 } 2552 2553 @Override 2554 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 2555 Rect rect = mChip.getDrawable().getBounds(); 2556 shadowSize.set(rect.width(), rect.height()); 2557 shadowTouchPoint.set(rect.centerX(), rect.centerY()); 2558 } 2559 2560 @Override 2561 public void onDrawShadow(Canvas canvas) { 2562 mChip.getDrawable().draw(canvas); 2563 } 2564 } 2565 2566 private void showCopyDialog(final String address) { 2567 mCopyAddress = address; 2568 mCopyDialog.setTitle(address); 2569 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout); 2570 mCopyDialog.setCancelable(true); 2571 mCopyDialog.setCanceledOnTouchOutside(true); 2572 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1); 2573 button.setOnClickListener(this); 2574 int btnTitleId; 2575 if (isPhoneQuery()) { 2576 btnTitleId = R.string.copy_number; 2577 } else { 2578 btnTitleId = R.string.copy_email; 2579 } 2580 String buttonTitle = getContext().getResources().getString(btnTitleId); 2581 button.setText(buttonTitle); 2582 mCopyDialog.setOnDismissListener(this); 2583 mCopyDialog.show(); 2584 } 2585 2586 @Override 2587 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2588 // Do nothing. 2589 return false; 2590 } 2591 2592 @Override 2593 public void onShowPress(MotionEvent e) { 2594 // Do nothing. 2595 } 2596 2597 @Override 2598 public boolean onSingleTapUp(MotionEvent e) { 2599 // Do nothing. 2600 return false; 2601 } 2602 2603 @Override 2604 public void onDismiss(DialogInterface dialog) { 2605 mCopyAddress = null; 2606 } 2607 2608 @Override 2609 public void onClick(View v) { 2610 // Copy this to the clipboard. 2611 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2612 Context.CLIPBOARD_SERVICE); 2613 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2614 mCopyDialog.dismiss(); 2615 } 2616 2617 protected boolean isPhoneQuery() { 2618 return getAdapter() != null 2619 && ((BaseRecipientAdapter) getAdapter()).getQueryType() 2620 == BaseRecipientAdapter.QUERY_TYPE_PHONE; 2621 } 2622} 2623