RecipientEditTextView.java revision ccb8e237ec80934d1c983bb61f66b75541786ddc
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.Spanned; 47import android.text.TextPaint; 48import android.text.TextUtils; 49import android.text.TextWatcher; 50import android.text.method.QwertyKeyListener; 51import android.text.style.ImageSpan; 52import android.text.util.Rfc822Token; 53import android.text.util.Rfc822Tokenizer; 54import android.util.AttributeSet; 55import android.util.Log; 56import android.util.Patterns; 57import android.view.ActionMode; 58import android.view.ActionMode.Callback; 59import android.view.DragEvent; 60import android.view.GestureDetector; 61import android.view.KeyEvent; 62import android.view.LayoutInflater; 63import android.view.Menu; 64import android.view.MenuItem; 65import android.view.MotionEvent; 66import android.view.View; 67import android.view.View.OnClickListener; 68import android.view.ViewParent; 69import android.view.inputmethod.EditorInfo; 70import android.view.inputmethod.InputConnection; 71import android.widget.AdapterView; 72import android.widget.AdapterView.OnItemClickListener; 73import android.widget.Button; 74import android.widget.ListAdapter; 75import android.widget.ListPopupWindow; 76import android.widget.ListView; 77import android.widget.MultiAutoCompleteTextView; 78import android.widget.ScrollView; 79import android.widget.TextView; 80 81import java.util.ArrayList; 82import java.util.Arrays; 83import java.util.Collection; 84import java.util.Collections; 85import java.util.Comparator; 86import java.util.HashMap; 87import java.util.HashSet; 88import java.util.Set; 89import java.util.regex.Matcher; 90 91/** 92 * RecipientEditTextView is an auto complete text view for use with applications 93 * that use the new Chips UI for addressing a message to recipients. 94 */ 95public class RecipientEditTextView extends MultiAutoCompleteTextView implements 96 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, 97 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener, 98 TextView.OnEditorActionListener { 99 100 private static final char COMMIT_CHAR_COMMA = ','; 101 102 private static final char NAME_WRAPPER_CHAR = '"'; 103 104 private static final char COMMIT_CHAR_SEMICOLON = ';'; 105 106 private static final char COMMIT_CHAR_SPACE = ' '; 107 108 private static final String TAG = "RecipientEditTextView"; 109 110 private static int DISMISS = "dismiss".hashCode(); 111 112 private static final long DISMISS_DELAY = 300; 113 114 // TODO: get correct number/ algorithm from with UX. 115 // Visible for testing. 116 /*package*/ static final int CHIP_LIMIT = 2; 117 118 private static final int MAX_CHIPS_PARSED = 50; 119 120 private static int sSelectedTextColor = -1; 121 122 // Resources for displaying chips. 123 private Drawable mChipBackground = null; 124 125 private Drawable mChipDelete = null; 126 127 private Drawable mInvalidChipBackground; 128 129 private Drawable mChipBackgroundPressed; 130 131 private float mChipHeight; 132 133 private float mChipFontSize; 134 135 private float mLineSpacingExtra; 136 137 private int mChipPadding; 138 139 private Tokenizer mTokenizer; 140 141 private Validator mValidator; 142 143 private RecipientChip mSelectedChip; 144 145 private int mAlternatesLayout; 146 147 private Bitmap mDefaultContactPhoto; 148 149 private ImageSpan mMoreChip; 150 151 private TextView mMoreItem; 152 153 private final ArrayList<String> mPendingChips = new ArrayList<String>(); 154 155 private Handler mHandler; 156 157 private int mPendingChipsCount = 0; 158 159 private boolean mNoChips = false; 160 161 private ListPopupWindow mAlternatesPopup; 162 163 private ListPopupWindow mAddressPopup; 164 165 private ArrayList<RecipientChip> mTemporaryRecipients; 166 167 private ArrayList<RecipientChip> mRemovedSpans; 168 169 private boolean mShouldShrink = true; 170 171 // Chip copy fields. 172 private GestureDetector mGestureDetector; 173 174 private Dialog mCopyDialog; 175 176 private String mCopyAddress; 177 178 /** 179 * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a 180 * selected chip. 181 */ 182 private OnItemClickListener mAlternatesListener; 183 184 private int mCheckedItem; 185 186 private TextWatcher mTextWatcher; 187 188 // Obtain the enclosing scroll view, if it exists, so that the view can be 189 // scrolled to show the last line of chips content. 190 private ScrollView mScrollView; 191 192 private boolean mTriedGettingScrollView; 193 194 private boolean mDragEnabled = false; 195 196 private final Runnable mAddTextWatcher = new Runnable() { 197 @Override 198 public void run() { 199 if (mTextWatcher == null) { 200 mTextWatcher = new RecipientTextWatcher(); 201 addTextChangedListener(mTextWatcher); 202 } 203 } 204 }; 205 206 private IndividualReplacementTask mIndividualReplacements; 207 208 private Runnable mHandlePendingChips = new Runnable() { 209 210 @Override 211 public void run() { 212 handlePendingChips(); 213 } 214 215 }; 216 217 private Runnable mDelayedShrink = new Runnable() { 218 219 @Override 220 public void run() { 221 shrink(); 222 } 223 224 }; 225 226 private int mMaxLines; 227 228 public RecipientEditTextView(Context context, AttributeSet attrs) { 229 super(context, attrs); 230 setChipDimensions(context, attrs); 231 if (sSelectedTextColor == -1) { 232 sSelectedTextColor = context.getResources().getColor(android.R.color.white); 233 } 234 mAlternatesPopup = new ListPopupWindow(context); 235 mAddressPopup = new ListPopupWindow(context); 236 mCopyDialog = new Dialog(context); 237 mAlternatesListener = new OnItemClickListener() { 238 @Override 239 public void onItemClick(AdapterView<?> adapterView,View view, int position, 240 long rowId) { 241 mAlternatesPopup.setOnItemClickListener(null); 242 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) 243 .getRecipientEntry(position)); 244 Message delayed = Message.obtain(mHandler, DISMISS); 245 delayed.obj = mAlternatesPopup; 246 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); 247 clearComposingText(); 248 } 249 }; 250 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 251 setOnItemClickListener(this); 252 setCustomSelectionActionModeCallback(this); 253 mHandler = new Handler() { 254 @Override 255 public void handleMessage(Message msg) { 256 if (msg.what == DISMISS) { 257 ((ListPopupWindow) msg.obj).dismiss(); 258 return; 259 } 260 super.handleMessage(msg); 261 } 262 }; 263 mTextWatcher = new RecipientTextWatcher(); 264 addTextChangedListener(mTextWatcher); 265 mGestureDetector = new GestureDetector(context, this); 266 setOnEditorActionListener(this); 267 mMaxLines = getLineCount(); 268 } 269 270 @Override 271 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) { 272 if (action == EditorInfo.IME_ACTION_DONE) { 273 if (commitDefault()) { 274 return true; 275 } 276 if (mSelectedChip != null) { 277 clearSelectedChip(); 278 return true; 279 } else if (focusNext()) { 280 return true; 281 } 282 } 283 return false; 284 } 285 286 @Override 287 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 288 InputConnection connection = super.onCreateInputConnection(outAttrs); 289 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION; 290 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) { 291 // clear the existing action 292 outAttrs.imeOptions ^= imeActions; 293 // set the DONE action 294 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 295 } 296 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) { 297 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION; 298 } 299 outAttrs.actionLabel = getContext().getString(R.string.done); 300 return connection; 301 } 302 303 /*package*/ RecipientChip getLastChip() { 304 RecipientChip last = null; 305 RecipientChip[] chips = getSortedRecipients(); 306 if (chips != null && chips.length > 0) { 307 last = chips[chips.length - 1]; 308 } 309 return last; 310 } 311 312 @Override 313 public void onSelectionChanged(int start, int end) { 314 // When selection changes, see if it is inside the chips area. 315 // If so, move the cursor back after the chips again. 316 RecipientChip last = getLastChip(); 317 if (last != null && start < getSpannable().getSpanEnd(last)) { 318 // Grab the last chip and set the cursor to after it. 319 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length())); 320 } 321 super.onSelectionChanged(start, end); 322 } 323 324 @Override 325 public void onRestoreInstanceState(Parcelable state) { 326 if (!TextUtils.isEmpty(getText())) { 327 super.onRestoreInstanceState(null); 328 } else { 329 super.onRestoreInstanceState(state); 330 } 331 } 332 333 @Override 334 public Parcelable onSaveInstanceState() { 335 // If the user changes orientation while they are editing, just roll back the selection. 336 clearSelectedChip(); 337 return super.onSaveInstanceState(); 338 } 339 340 /** 341 * Convenience method: Append the specified text slice to the TextView's 342 * display buffer, upgrading it to BufferType.EDITABLE if it was 343 * not already editable. Commas are excluded as they are added automatically 344 * by the view. 345 */ 346 @Override 347 public void append(CharSequence text, int start, int end) { 348 // We don't care about watching text changes while appending. 349 if (mTextWatcher != null) { 350 removeTextChangedListener(mTextWatcher); 351 } 352 super.append(text, start, end); 353 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) { 354 String displayString = text.toString(); 355 int separatorPos = displayString.lastIndexOf(COMMIT_CHAR_COMMA); 356 // Verify that the separator pos is not within ""; if it is, look 357 // past the closing quote. If there is no comma past ", this string 358 // will resolve to an error chip. 359 if (separatorPos > -1) { 360 String parseDisplayString = displayString.substring(separatorPos); 361 int endQuotedTextPos = parseDisplayString.indexOf(NAME_WRAPPER_CHAR); 362 if (endQuotedTextPos > separatorPos) { 363 separatorPos = parseDisplayString.lastIndexOf(COMMIT_CHAR_COMMA, 364 endQuotedTextPos); 365 } 366 } 367 if (!TextUtils.isEmpty(displayString) 368 && TextUtils.getTrimmedLength(displayString) > 0) { 369 mPendingChipsCount++; 370 mPendingChips.add(text.toString()); 371 } 372 } 373 // Put a message on the queue to make sure we ALWAYS handle pending 374 // chips. 375 if (mPendingChipsCount > 0) { 376 postHandlePendingChips(); 377 } 378 mHandler.post(mAddTextWatcher); 379 } 380 381 @Override 382 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { 383 super.onFocusChanged(hasFocus, direction, previous); 384 if (!hasFocus) { 385 shrink(); 386 } else { 387 expand(); 388 } 389 } 390 391 @Override 392 public void performValidation() { 393 // Do nothing. Chips handles its own validation. 394 } 395 396 private void shrink() { 397 if (mTokenizer == null) { 398 return; 399 } 400 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1; 401 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT 402 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) { 403 clearSelectedChip(); 404 } else { 405 if (getWidth() <= 0) { 406 // We don't have the width yet which means the view hasn't been drawn yet 407 // and there is no reason to attempt to commit chips yet. 408 // This focus lost must be the result of an orientation change 409 // or an initial rendering. 410 // Re-post the shrink for later. 411 mHandler.removeCallbacks(mDelayedShrink); 412 mHandler.post(mDelayedShrink); 413 return; 414 } 415 // Reset any pending chips as they would have been handled 416 // when the field lost focus. 417 if (mPendingChipsCount > 0) { 418 postHandlePendingChips(); 419 } else { 420 Editable editable = getText(); 421 int end = getSelectionEnd(); 422 int start = mTokenizer.findTokenStart(editable, end); 423 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 424 if ((chips == null || chips.length == 0)) { 425 Editable text = getText(); 426 int whatEnd = mTokenizer.findTokenEnd(text, start); 427 // This token was already tokenized, so skip past the ending token. 428 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') { 429 whatEnd = movePastTerminators(whatEnd); 430 } 431 // In the middle of chip; treat this as an edit 432 // and commit the whole token. 433 int selEnd = getSelectionEnd(); 434 if (whatEnd != selEnd) { 435 handleEdit(start, whatEnd); 436 } else { 437 commitChip(start, end, editable); 438 } 439 } 440 } 441 mHandler.post(mAddTextWatcher); 442 } 443 createMoreChip(); 444 } 445 446 private void expand() { 447 if (mShouldShrink) { 448 setMaxLines(Integer.MAX_VALUE); 449 } 450 removeMoreChip(); 451 setCursorVisible(true); 452 Editable text = getText(); 453 setSelection(text != null && text.length() > 0 ? text.length() : 0); 454 // If there are any temporary chips, try replacing them now that the user 455 // has expanded the field. 456 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) { 457 new RecipientReplacementTask().execute(); 458 mTemporaryRecipients = null; 459 } 460 } 461 462 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) { 463 paint.setTextSize(mChipFontSize); 464 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) { 465 Log.d(TAG, "Max width is negative: " + maxWidth); 466 } 467 return TextUtils.ellipsize(text, paint, maxWidth, 468 TextUtils.TruncateAt.END); 469 } 470 471 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 472 // Ellipsize the text so that it takes AT MOST the entire width of the 473 // autocomplete text entry area. Make sure to leave space for padding 474 // on the sides. 475 int height = (int) mChipHeight; 476 int deleteWidth = height; 477 float[] widths = new float[1]; 478 paint.getTextWidths(" ", widths); 479 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint, 480 calculateAvailableWidth(true) - deleteWidth - widths[0]); 481 482 // Make sure there is a minimum chip width so the user can ALWAYS 483 // tap a chip without difficulty. 484 int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 485 ellipsizedText.length())) 486 + (mChipPadding * 2) + deleteWidth); 487 488 // Create the background of the chip. 489 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 490 Canvas canvas = new Canvas(tmpBitmap); 491 if (mChipBackgroundPressed != null) { 492 mChipBackgroundPressed.setBounds(0, 0, width, height); 493 mChipBackgroundPressed.draw(canvas); 494 paint.setColor(sSelectedTextColor); 495 // Vertically center the text in the chip. 496 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 497 getTextYOffset((String) ellipsizedText, paint, height), paint); 498 // Make the delete a square. 499 Rect backgroundPadding = new Rect(); 500 mChipBackgroundPressed.getPadding(backgroundPadding); 501 mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left, 502 0 + backgroundPadding.top, 503 width - backgroundPadding.right, 504 height - backgroundPadding.bottom); 505 mChipDelete.draw(canvas); 506 } else { 507 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 508 } 509 return tmpBitmap; 510 } 511 512 513 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout, 514 boolean leaveBlankIconSpacer) { 515 // Ellipsize the text so that it takes AT MOST the entire width of the 516 // autocomplete text entry area. Make sure to leave space for padding 517 // on the sides. 518 int height = (int) mChipHeight; 519 int iconWidth = height; 520 float[] widths = new float[1]; 521 paint.getTextWidths(" ", widths); 522 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint, 523 calculateAvailableWidth(false) - iconWidth - widths[0]); 524 // Make sure there is a minimum chip width so the user can ALWAYS 525 // tap a chip without difficulty. 526 int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 527 ellipsizedText.length())) 528 + (mChipPadding * 2) + iconWidth); 529 530 // Create the background of the chip. 531 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 532 Canvas canvas = new Canvas(tmpBitmap); 533 Drawable background = getChipBackground(contact); 534 if (background != null) { 535 background.setBounds(0, 0, width, height); 536 background.draw(canvas); 537 538 // Don't draw photos for recipients that have been typed in OR generated on the fly. 539 long contactId = contact.getContactId(); 540 boolean drawPhotos = isPhoneQuery() ? 541 contactId != RecipientEntry.INVALID_CONTACT 542 : (contactId != RecipientEntry.INVALID_CONTACT 543 && (contactId != RecipientEntry.GENERATED_CONTACT && 544 !TextUtils.isEmpty(contact.getDisplayName()))); 545 if (drawPhotos) { 546 byte[] photoBytes = contact.getPhotoBytes(); 547 // There may not be a photo yet if anything but the first contact address 548 // was selected. 549 if (photoBytes == null && contact.getPhotoThumbnailUri() != null) { 550 // TODO: cache this in the recipient entry? 551 ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact 552 .getPhotoThumbnailUri()); 553 photoBytes = contact.getPhotoBytes(); 554 } 555 556 Bitmap photo; 557 if (photoBytes != null) { 558 photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); 559 } else { 560 // TODO: can the scaled down default photo be cached? 561 photo = mDefaultContactPhoto; 562 } 563 // Draw the photo on the left side. 564 if (photo != null) { 565 RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight()); 566 Rect backgroundPadding = new Rect(); 567 mChipBackground.getPadding(backgroundPadding); 568 RectF dst = new RectF(width - iconWidth + backgroundPadding.left, 569 0 + backgroundPadding.top, 570 width - backgroundPadding.right, 571 height - backgroundPadding.bottom); 572 Matrix matrix = new Matrix(); 573 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL); 574 canvas.drawBitmap(photo, matrix, paint); 575 } 576 } else if (!leaveBlankIconSpacer || isPhoneQuery()) { 577 iconWidth = 0; 578 } 579 paint.setColor(getContext().getResources().getColor(android.R.color.black)); 580 // Vertically center the text in the chip. 581 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 582 getTextYOffset((String)ellipsizedText, paint, height), paint); 583 } else { 584 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 585 } 586 return tmpBitmap; 587 } 588 589 /** 590 * Get the background drawable for a RecipientChip. 591 */ 592 // Visible for testing. 593 /* package */Drawable getChipBackground(RecipientEntry contact) { 594 return contact.isValid() ? mChipBackground : mInvalidChipBackground; 595 } 596 597 private float getTextYOffset(String text, TextPaint paint, int height) { 598 Rect bounds = new Rect(); 599 paint.getTextBounds(text, 0, text.length(), bounds); 600 int textHeight = bounds.bottom - bounds.top ; 601 return height - ((height - textHeight) / 2) - (int)paint.descent(); 602 } 603 604 private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed, 605 boolean leaveIconSpace) throws NullPointerException { 606 if (mChipBackground == null) { 607 throw new NullPointerException( 608 "Unable to render any chips as setChipDimensions was not called."); 609 } 610 Layout layout = getLayout(); 611 612 TextPaint paint = getPaint(); 613 float defaultSize = paint.getTextSize(); 614 int defaultColor = paint.getColor(); 615 616 Bitmap tmpBitmap; 617 if (pressed) { 618 tmpBitmap = createSelectedChip(contact, paint, layout); 619 620 } else { 621 tmpBitmap = createUnselectedChip(contact, paint, layout, leaveIconSpace); 622 } 623 624 // Pass the full text, un-ellipsized, to the chip. 625 Drawable result = new BitmapDrawable(getResources(), tmpBitmap); 626 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight()); 627 RecipientChip recipientChip = new RecipientChip(result, contact, offset); 628 // Return text to the original size. 629 paint.setTextSize(defaultSize); 630 paint.setColor(defaultColor); 631 return recipientChip; 632 } 633 634 /** 635 * Calculate the bottom of the line the chip will be located on using: 636 * 1) which line the chip appears on 637 * 2) the height of a chip 638 * 3) padding built into the edit text view 639 */ 640 private int calculateOffsetFromBottom(int line) { 641 // Line offsets start at zero. 642 int actualLine = getLineCount() - (line + 1); 643 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop()) 644 + getDropDownVerticalOffset(); 645 } 646 647 /** 648 * Get the max amount of space a chip can take up. The formula takes into 649 * account the width of the EditTextView, any view padding, and padding 650 * that will be added to the chip. 651 */ 652 private float calculateAvailableWidth(boolean pressed) { 653 return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2); 654 } 655 656 657 private void setChipDimensions(Context context, AttributeSet attrs) { 658 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0, 659 0); 660 Resources r = getContext().getResources(); 661 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground); 662 if (mChipBackground == null) { 663 mChipBackground = r.getDrawable(R.drawable.chip_background); 664 } 665 mChipBackgroundPressed = a 666 .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed); 667 if (mChipBackgroundPressed == null) { 668 mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected); 669 } 670 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete); 671 if (mChipDelete == null) { 672 mChipDelete = r.getDrawable(R.drawable.chip_delete); 673 } 674 mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1); 675 if (mChipPadding == -1) { 676 mChipPadding = (int) r.getDimension(R.dimen.chip_padding); 677 } 678 mAlternatesLayout = a.getResourceId(R.styleable.RecipientEditTextView_chipAlternatesLayout, 679 -1); 680 if (mAlternatesLayout == -1) { 681 mAlternatesLayout = R.layout.chips_alternate_item; 682 } 683 684 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture); 685 686 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null); 687 688 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1); 689 if (mChipHeight == -1) { 690 mChipHeight = r.getDimension(R.dimen.chip_height); 691 } 692 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1); 693 if (mChipFontSize == -1) { 694 mChipFontSize = r.getDimension(R.dimen.chip_text_size); 695 } 696 mInvalidChipBackground = a 697 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground); 698 if (mInvalidChipBackground == null) { 699 mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid); 700 } 701 mLineSpacingExtra = context.getResources().getDimension(R.dimen.line_spacing_extra); 702 a.recycle(); 703 } 704 705 // Visible for testing. 706 /* package */ void setMoreItem(TextView moreItem) { 707 mMoreItem = moreItem; 708 } 709 710 711 // Visible for testing. 712 /* package */ void setChipBackground(Drawable chipBackground) { 713 mChipBackground = chipBackground; 714 } 715 716 // Visible for testing. 717 /* package */ void setChipHeight(int height) { 718 mChipHeight = height; 719 } 720 721 /** 722 * Set whether to shrink the recipients field such that at most 723 * one line of recipients chips are shown when the field loses 724 * focus. By default, the number of displayed recipients will be 725 * limited and a "more" chip will be shown when focus is lost. 726 * @param shrink 727 */ 728 public void setOnFocusListShrinkRecipients(boolean shrink) { 729 mShouldShrink = shrink; 730 } 731 732 @Override 733 public void onSizeChanged(int width, int height, int oldw, int oldh) { 734 super.onSizeChanged(width, height, oldw, oldh); 735 if (width != 0 && height != 0) { 736 if (mPendingChipsCount > 0) { 737 postHandlePendingChips(); 738 } else { 739 checkChipWidths(); 740 } 741 } 742 // Try to find the scroll view parent, if it exists. 743 if (mScrollView == null && !mTriedGettingScrollView) { 744 ViewParent parent = getParent(); 745 while (parent != null && !(parent instanceof ScrollView)) { 746 parent = parent.getParent(); 747 } 748 if (parent != null) { 749 mScrollView = (ScrollView) parent; 750 } 751 mTriedGettingScrollView = true; 752 } 753 } 754 755 private void postHandlePendingChips() { 756 mHandler.removeCallbacks(mHandlePendingChips); 757 mHandler.post(mHandlePendingChips); 758 } 759 760 private void checkChipWidths() { 761 // Check the widths of the associated chips. 762 RecipientChip[] chips = getSortedRecipients(); 763 if (chips != null) { 764 Rect bounds; 765 for (RecipientChip chip : chips) { 766 bounds = chip.getDrawable().getBounds(); 767 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) { 768 // Need to redraw that chip. 769 replaceChip(chip, chip.getEntry()); 770 } 771 } 772 } 773 } 774 775 // Visible for testing. 776 /*package*/ void handlePendingChips() { 777 if (getViewWidth() <= 0) { 778 // The widget has not been sized yet. 779 // This will be called as a result of onSizeChanged 780 // at a later point. 781 return; 782 } 783 if (mPendingChipsCount <= 0) { 784 return; 785 } 786 787 synchronized (mPendingChips) { 788 Editable editable = getText(); 789 // Tokenize! 790 if (mPendingChipsCount <= MAX_CHIPS_PARSED) { 791 for (int i = 0; i < mPendingChips.size(); i++) { 792 String current = mPendingChips.get(i); 793 int tokenStart = editable.toString().indexOf(current); 794 int tokenEnd = tokenStart + current.length(); 795 if (tokenStart >= 0) { 796 // When we have a valid token, include it with the token 797 // to the left. 798 if (tokenEnd < editable.length() - 2 799 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { 800 tokenEnd++; 801 } 802 createReplacementChip(tokenStart, tokenEnd, editable); 803 } 804 mPendingChipsCount--; 805 } 806 sanitizeEnd(); 807 } else { 808 mNoChips = true; 809 } 810 811 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0 812 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { 813 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { 814 new RecipientReplacementTask().execute(); 815 mTemporaryRecipients = null; 816 } else { 817 // Create the "more" chip 818 mIndividualReplacements = new IndividualReplacementTask(); 819 mIndividualReplacements.execute(new ArrayList<RecipientChip>( 820 mTemporaryRecipients.subList(0, CHIP_LIMIT))); 821 if (mTemporaryRecipients.size() > CHIP_LIMIT) { 822 mTemporaryRecipients = new ArrayList<RecipientChip>( 823 mTemporaryRecipients.subList(CHIP_LIMIT, 824 mTemporaryRecipients.size())); 825 } else { 826 mTemporaryRecipients = null; 827 } 828 createMoreChip(); 829 } 830 } else { 831 // There are too many recipients to look up, so just fall back 832 // to showing addresses for all of them. 833 mTemporaryRecipients = null; 834 createMoreChip(); 835 } 836 mPendingChipsCount = 0; 837 mPendingChips.clear(); 838 } 839 } 840 841 // Visible for testing. 842 /*package*/ int getViewWidth() { 843 return getWidth(); 844 } 845 846 /** 847 * Remove any characters after the last valid chip. 848 */ 849 // Visible for testing. 850 /*package*/ void sanitizeEnd() { 851 // Don't sanitize while we are waiting for pending chips to complete. 852 if (mPendingChipsCount > 0) { 853 return; 854 } 855 // Find the last chip; eliminate any commit characters after it. 856 RecipientChip[] chips = getSortedRecipients(); 857 if (chips != null && chips.length > 0) { 858 int end; 859 ImageSpan lastSpan; 860 mMoreChip = getMoreChip(); 861 if (mMoreChip != null) { 862 lastSpan = mMoreChip; 863 } else { 864 lastSpan = getLastChip(); 865 } 866 end = getSpannable().getSpanEnd(lastSpan); 867 Editable editable = getText(); 868 int length = editable.length(); 869 if (length > end) { 870 // See what characters occur after that and eliminate them. 871 if (Log.isLoggable(TAG, Log.DEBUG)) { 872 Log.d(TAG, "There were extra characters after the last tokenizable entry." 873 + editable); 874 } 875 editable.delete(end + 1, length); 876 } 877 } 878 } 879 880 /** 881 * Create a chip that represents just the email address of a recipient. At some later 882 * point, this chip will be attached to a real contact entry, if one exists. 883 */ 884 private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { 885 if (alreadyHasChip(tokenStart, tokenEnd)) { 886 // There is already a chip present at this location. 887 // Don't recreate it. 888 return; 889 } 890 String token = editable.toString().substring(tokenStart, tokenEnd); 891 int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); 892 if (commitCharIndex == token.length() - 1) { 893 token = token.substring(0, token.length() - 1); 894 } 895 RecipientEntry entry = createTokenizedEntry(token); 896 if (entry != null) { 897 String destText = createAddressText(entry); 898 SpannableString chipText = new SpannableString(destText); 899 int end = getSelectionEnd(); 900 int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0; 901 RecipientChip chip = null; 902 try { 903 if (!mNoChips) { 904 /* leave space for the contact icon if this is not just an email address */ 905 chip = constructChipSpan( 906 entry, 907 start, 908 false, 909 TextUtils.isEmpty(entry.getDisplayName()) 910 || TextUtils.equals(entry.getDisplayName(), 911 entry.getDestination())); 912 } 913 } catch (NullPointerException e) { 914 Log.e(TAG, e.getMessage(), e); 915 } 916 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 917 // Add this chip to the list of entries "to replace" 918 if (chip != null) { 919 if (mTemporaryRecipients == null) { 920 mTemporaryRecipients = new ArrayList<RecipientChip>(); 921 } 922 chip.setOriginalText(chipText.toString()); 923 mTemporaryRecipients.add(chip); 924 } 925 } 926 } 927 928 private static boolean isPhoneNumber(String number) { 929 // TODO: replace this function with libphonenumber's isPossibleNumber (see 930 // PhoneNumberUtil). One complication is that it requires the sender's region which 931 // comes from the CurrentCountryIso. For now, let's just do this simple match. 932 if (TextUtils.isEmpty(number)) { 933 return false; 934 } 935 936 Matcher match = Patterns.PHONE.matcher(number); 937 return match.matches(); 938 } 939 940 private RecipientEntry createTokenizedEntry(String token) { 941 if (TextUtils.isEmpty(token)) { 942 return null; 943 } 944 if (isPhoneQuery() && isPhoneNumber(token)) { 945 return RecipientEntry.constructFakeEntry(token, true); 946 } 947 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 948 String display = null; 949 boolean isValid = isValid(token); 950 if (isValid && tokens != null && tokens.length > 0) { 951 // If we can get a name from tokenizing, then generate an entry from 952 // this. 953 display = tokens[0].getName(); 954 if (!TextUtils.isEmpty(display)) { 955 if (!isPhoneQuery()) { 956 if (!TextUtils.isEmpty(token)) { 957 token = token.trim(); 958 } 959 char charAt = token.charAt(token.length() - 1); 960 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 961 token = token.substring(0, token.length() - 1); 962 } 963 } 964 return RecipientEntry.constructGeneratedEntry(display, token, isValid); 965 } else { 966 display = tokens[0].getAddress(); 967 if (!TextUtils.isEmpty(display)) { 968 return RecipientEntry.constructFakeEntry(display, isValid); 969 } 970 } 971 } 972 // Unable to validate the token or to create a valid token from it. 973 // Just create a chip the user can edit. 974 String validatedToken = null; 975 if (mValidator != null && !isValid) { 976 // Try fixing up the entry using the validator. 977 validatedToken = mValidator.fixText(token).toString(); 978 if (!TextUtils.isEmpty(validatedToken)) { 979 if (validatedToken.contains(token)) { 980 // protect against the case of a validator with a null 981 // domain, 982 // which doesn't add a domain to the token 983 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 984 if (tokenized.length > 0) { 985 validatedToken = tokenized[0].getAddress(); 986 isValid = true; 987 } 988 } else { 989 // We ran into a case where the token was invalid and 990 // removed 991 // by the validator. In this case, just use the original 992 // token 993 // and let the user sort out the error chip. 994 validatedToken = null; 995 isValid = false; 996 } 997 } 998 } 999 // Otherwise, fallback to just creating an editable email address chip. 1000 return RecipientEntry.constructFakeEntry( 1001 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid); 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, isValid(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, item.isValid()); 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, item.isValid()); 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, 1888 isValid(text.toString())), -1); 1889 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1890 int start = getChipStart(currentChip); 1891 int end = getChipEnd(currentChip); 1892 getSpannable().removeSpan(currentChip); 1893 RecipientChip newChip; 1894 try { 1895 if (mNoChips) { 1896 return null; 1897 } 1898 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1899 } catch (NullPointerException e) { 1900 Log.e(TAG, e.getMessage(), e); 1901 return null; 1902 } 1903 Editable editable = getText(); 1904 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1905 if (start == -1 || end == -1) { 1906 Log.d(TAG, "The chip being selected no longer exists but should."); 1907 } else { 1908 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1909 } 1910 newChip.setSelected(true); 1911 if (shouldShowEditableText(newChip)) { 1912 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1913 } 1914 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1915 setCursorVisible(false); 1916 return newChip; 1917 } else { 1918 int start = getChipStart(currentChip); 1919 int end = getChipEnd(currentChip); 1920 getSpannable().removeSpan(currentChip); 1921 RecipientChip newChip; 1922 try { 1923 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1924 } catch (NullPointerException e) { 1925 Log.e(TAG, e.getMessage(), e); 1926 return null; 1927 } 1928 Editable editable = getText(); 1929 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1930 if (start == -1 || end == -1) { 1931 Log.d(TAG, "The chip being selected no longer exists but should."); 1932 } else { 1933 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1934 } 1935 newChip.setSelected(true); 1936 if (shouldShowEditableText(newChip)) { 1937 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1938 } 1939 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1940 setCursorVisible(false); 1941 return newChip; 1942 } 1943 } 1944 1945 private boolean shouldShowEditableText(RecipientChip currentChip) { 1946 long contactId = currentChip.getContactId(); 1947 return contactId == RecipientEntry.INVALID_CONTACT 1948 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT); 1949 } 1950 1951 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1952 int width, Context context) { 1953 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1954 int bottom = calculateOffsetFromBottom(line); 1955 // Align the alternates popup with the left side of the View, 1956 // regardless of the position of the chip tapped. 1957 popup.setWidth(width); 1958 popup.setAnchorView(this); 1959 popup.setVerticalOffset(bottom); 1960 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1961 popup.setOnItemClickListener(new OnItemClickListener() { 1962 @Override 1963 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1964 unselectChip(currentChip); 1965 popup.dismiss(); 1966 } 1967 }); 1968 popup.show(); 1969 ListView listView = popup.getListView(); 1970 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1971 listView.setItemChecked(0, true); 1972 } 1973 1974 /** 1975 * Remove selection from this chip. Unselecting a RecipientChip will render 1976 * the chip without a delete icon and with an unfocused background. This is 1977 * called when the RecipientChip no longer has focus. 1978 */ 1979 private void unselectChip(RecipientChip chip) { 1980 int start = getChipStart(chip); 1981 int end = getChipEnd(chip); 1982 Editable editable = getText(); 1983 mSelectedChip = null; 1984 if (start == -1 || end == -1) { 1985 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing"); 1986 setSelection(editable.length()); 1987 commitDefault(); 1988 } else { 1989 getSpannable().removeSpan(chip); 1990 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1991 editable.removeSpan(chip); 1992 try { 1993 if (!mNoChips) { 1994 editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false), 1995 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1996 } 1997 } catch (NullPointerException e) { 1998 Log.e(TAG, e.getMessage(), e); 1999 } 2000 } 2001 setCursorVisible(true); 2002 setSelection(editable.length()); 2003 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 2004 mAlternatesPopup.dismiss(); 2005 } 2006 } 2007 2008 /** 2009 * Return whether a touch event was inside the delete target of 2010 * a selected chip. It is in the delete target if: 2011 * 1) the x and y points of the event are within the 2012 * delete assset. 2013 * 2) the point tapped would have caused a cursor to appear 2014 * right after the selected chip. 2015 * @return boolean 2016 */ 2017 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 2018 // Figure out the bounds of this chip and whether or not 2019 // the user clicked in the X portion. 2020 return chip.isSelected() && offset == getChipEnd(chip); 2021 } 2022 2023 /** 2024 * Remove the chip and any text associated with it from the RecipientEditTextView. 2025 */ 2026 // Visible for testing. 2027 /*pacakge*/ void removeChip(RecipientChip chip) { 2028 Spannable spannable = getSpannable(); 2029 int spanStart = spannable.getSpanStart(chip); 2030 int spanEnd = spannable.getSpanEnd(chip); 2031 Editable text = getText(); 2032 int toDelete = spanEnd; 2033 boolean wasSelected = chip == mSelectedChip; 2034 // Clear that there is a selected chip before updating any text. 2035 if (wasSelected) { 2036 mSelectedChip = null; 2037 } 2038 // Always remove trailing spaces when removing a chip. 2039 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') { 2040 toDelete++; 2041 } 2042 spannable.removeSpan(chip); 2043 if (spanStart >= 0 && toDelete > 0) { 2044 text.delete(spanStart, toDelete); 2045 } 2046 if (wasSelected) { 2047 clearSelectedChip(); 2048 } 2049 } 2050 2051 /** 2052 * Replace this currently selected chip with a new chip 2053 * that uses the contact data provided. 2054 */ 2055 // Visible for testing. 2056 /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) { 2057 boolean wasSelected = chip == mSelectedChip; 2058 if (wasSelected) { 2059 mSelectedChip = null; 2060 } 2061 int start = getChipStart(chip); 2062 int end = getChipEnd(chip); 2063 getSpannable().removeSpan(chip); 2064 Editable editable = getText(); 2065 CharSequence chipText = createChip(entry, false); 2066 if (chipText != null) { 2067 if (start == -1 || end == -1) { 2068 Log.e(TAG, "The chip to replace does not exist but should."); 2069 editable.insert(0, chipText); 2070 } else { 2071 if (!TextUtils.isEmpty(chipText)) { 2072 // There may be a space to replace with this chip's new 2073 // associated space. Check for it 2074 int toReplace = end; 2075 while (toReplace >= 0 && toReplace < editable.length() 2076 && editable.charAt(toReplace) == ' ') { 2077 toReplace++; 2078 } 2079 editable.replace(start, toReplace, chipText); 2080 } 2081 } 2082 } 2083 setCursorVisible(true); 2084 if (wasSelected) { 2085 clearSelectedChip(); 2086 } 2087 } 2088 2089 /** 2090 * Handle click events for a chip. When a selected chip receives a click 2091 * event, see if that event was in the delete icon. If so, delete it. 2092 * Otherwise, unselect the chip. 2093 */ 2094 public void onClick(RecipientChip chip, int offset, float x, float y) { 2095 if (chip.isSelected()) { 2096 if (isInDelete(chip, offset, x, y)) { 2097 removeChip(chip); 2098 } else { 2099 clearSelectedChip(); 2100 } 2101 } 2102 } 2103 2104 private boolean chipsPending() { 2105 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 2106 } 2107 2108 @Override 2109 public void removeTextChangedListener(TextWatcher watcher) { 2110 mTextWatcher = null; 2111 super.removeTextChangedListener(watcher); 2112 } 2113 2114 private class RecipientTextWatcher implements TextWatcher { 2115 2116 @Override 2117 public void afterTextChanged(Editable s) { 2118 // If the text has been set to null or empty, make sure we remove 2119 // all the spans we applied. 2120 if (TextUtils.isEmpty(s)) { 2121 // Remove all the chips spans. 2122 Spannable spannable = getSpannable(); 2123 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 2124 RecipientChip.class); 2125 for (RecipientChip chip : chips) { 2126 spannable.removeSpan(chip); 2127 } 2128 if (mMoreChip != null) { 2129 spannable.removeSpan(mMoreChip); 2130 } 2131 return; 2132 } 2133 // Get whether there are any recipients pending addition to the 2134 // view. If there are, don't do anything in the text watcher. 2135 if (chipsPending()) { 2136 return; 2137 } 2138 // If the user is editing a chip, don't clear it. 2139 if (mSelectedChip != null 2140 && shouldShowEditableText(mSelectedChip)) { 2141 setCursorVisible(true); 2142 setSelection(getText().length()); 2143 clearSelectedChip(); 2144 } 2145 int length = s.length(); 2146 // Make sure there is content there to parse and that it is 2147 // not just the commit character. 2148 if (length > 1) { 2149 char last; 2150 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 2151 int len = length() - 1; 2152 if (end != len) { 2153 last = s.charAt(end); 2154 } else { 2155 last = s.charAt(len); 2156 } 2157 if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { 2158 commitByCharacter(); 2159 } else if (last == COMMIT_CHAR_SPACE) { 2160 if (!isPhoneQuery()) { 2161 // Check if this is a valid email address. If it is, 2162 // commit it. 2163 String text = getText().toString(); 2164 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2165 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 2166 tokenStart)); 2167 if (!TextUtils.isEmpty(sub) && mValidator != null && 2168 mValidator.isValid(sub)) { 2169 commitByCharacter(); 2170 } 2171 } 2172 } 2173 } 2174 } 2175 2176 @Override 2177 public void onTextChanged(CharSequence s, int start, int before, int count) { 2178 // This is a delete; check to see if the insertion point is on a space 2179 // following a chip. 2180 if (before > count) { 2181 // If the item deleted is a space, and the thing before the 2182 // space is a chip, delete the entire span. 2183 int selStart = getSelectionStart(); 2184 RecipientChip[] repl = getSpannable().getSpans(selStart, selStart, 2185 RecipientChip.class); 2186 if (repl.length > 0) { 2187 // There is a chip there! Just remove it. 2188 Editable editable = getText(); 2189 // Add the separator token. 2190 int tokenStart = mTokenizer.findTokenStart(editable, selStart); 2191 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart); 2192 tokenEnd = tokenEnd + 1; 2193 if (tokenEnd > editable.length()) { 2194 tokenEnd = editable.length(); 2195 } 2196 editable.delete(tokenStart, tokenEnd); 2197 getSpannable().removeSpan(repl[0]); 2198 } 2199 } else if (count > before) { 2200 scrollBottomIntoView(); 2201 } 2202 } 2203 2204 @Override 2205 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 2206 // Do nothing. 2207 } 2208 } 2209 2210 private void scrollBottomIntoView() { 2211 if (mScrollView != null) { 2212 mScrollView.scrollBy(0, (int) (getLineCount() * mChipHeight)); 2213 } 2214 } 2215 2216 /** 2217 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}. 2218 */ 2219 private void handlePasteClip(ClipData clip) { 2220 removeTextChangedListener(mTextWatcher); 2221 2222 if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ 2223 for (int i = 0; i < clip.getItemCount(); i++) { 2224 CharSequence paste = clip.getItemAt(i).getText(); 2225 if (paste != null) { 2226 int start = getSelectionStart(); 2227 int end = getSelectionEnd(); 2228 Editable editable = getText(); 2229 if (start >= 0 && end >= 0 && start != end) { 2230 editable.append(paste, start, end); 2231 } else { 2232 editable.insert(end, paste); 2233 } 2234 handlePasteAndReplace(); 2235 } 2236 } 2237 } 2238 2239 mHandler.post(mAddTextWatcher); 2240 } 2241 2242 @Override 2243 public boolean onTextContextMenuItem(int id) { 2244 if (id == android.R.id.paste) { 2245 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2246 Context.CLIPBOARD_SERVICE); 2247 handlePasteClip(clipboard.getPrimaryClip()); 2248 return true; 2249 } 2250 return super.onTextContextMenuItem(id); 2251 } 2252 2253 private void handlePasteAndReplace() { 2254 ArrayList<RecipientChip> created = handlePaste(); 2255 if (created != null && created.size() > 0) { 2256 // Perform reverse lookups on the pasted contacts. 2257 IndividualReplacementTask replace = new IndividualReplacementTask(); 2258 replace.execute(created); 2259 } 2260 } 2261 2262 // Visible for testing. 2263 /* package */ArrayList<RecipientChip> handlePaste() { 2264 String text = getText().toString(); 2265 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2266 String lastAddress = text.substring(originalTokenStart); 2267 int tokenStart = originalTokenStart; 2268 int prevTokenStart = tokenStart; 2269 RecipientChip findChip = null; 2270 ArrayList<RecipientChip> created = new ArrayList<RecipientChip>(); 2271 if (tokenStart != 0) { 2272 // There are things before this! 2273 while (tokenStart != 0 && findChip == null) { 2274 prevTokenStart = tokenStart; 2275 tokenStart = mTokenizer.findTokenStart(text, tokenStart); 2276 findChip = findChip(tokenStart); 2277 } 2278 if (tokenStart != originalTokenStart) { 2279 if (findChip != null) { 2280 tokenStart = prevTokenStart; 2281 } 2282 int tokenEnd; 2283 RecipientChip createdChip; 2284 while (tokenStart < originalTokenStart) { 2285 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(), 2286 tokenStart)); 2287 commitChip(tokenStart, tokenEnd, getText()); 2288 createdChip = findChip(tokenStart); 2289 if (createdChip == null) { 2290 break; 2291 } 2292 // +1 for the space at the end. 2293 tokenStart = getSpannable().getSpanEnd(createdChip) + 1; 2294 created.add(createdChip); 2295 } 2296 } 2297 } 2298 // Take a look at the last token. If the token has been completed with a 2299 // commit character, create a chip. 2300 if (isCompletedToken(lastAddress)) { 2301 Editable editable = getText(); 2302 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart); 2303 commitChip(tokenStart, editable.length(), editable); 2304 created.add(findChip(tokenStart)); 2305 } 2306 return created; 2307 } 2308 2309 // Visible for testing. 2310 /* package */int movePastTerminators(int tokenEnd) { 2311 if (tokenEnd >= length()) { 2312 return tokenEnd; 2313 } 2314 char atEnd = getText().toString().charAt(tokenEnd); 2315 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) { 2316 tokenEnd++; 2317 } 2318 // This token had not only an end token character, but also a space 2319 // separating it from the next token. 2320 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') { 2321 tokenEnd++; 2322 } 2323 return tokenEnd; 2324 } 2325 2326 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 2327 private RecipientChip createFreeChip(RecipientEntry entry) { 2328 try { 2329 if (mNoChips) { 2330 return null; 2331 } 2332 return constructChipSpan(entry, -1, false, 2333 false /*leave space for contact icon */); 2334 } catch (NullPointerException e) { 2335 Log.e(TAG, e.getMessage(), e); 2336 return null; 2337 } 2338 } 2339 2340 @Override 2341 protected Void doInBackground(Void... params) { 2342 if (mIndividualReplacements != null) { 2343 mIndividualReplacements.cancel(true); 2344 } 2345 // For each chip in the list, look up the matching contact. 2346 // If there is a match, replace that chip with the matching 2347 // chip. 2348 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 2349 RecipientChip[] existingChips = getSortedRecipients(); 2350 for (int i = 0; i < existingChips.length; i++) { 2351 originalRecipients.add(existingChips[i]); 2352 } 2353 if (mRemovedSpans != null) { 2354 originalRecipients.addAll(mRemovedSpans); 2355 } 2356 ArrayList<String> addresses = new ArrayList<String>(); 2357 RecipientChip chip; 2358 for (int i = 0; i < originalRecipients.size(); i++) { 2359 chip = originalRecipients.get(i); 2360 if (chip != null) { 2361 addresses.add(createAddressText(chip.getEntry())); 2362 } 2363 } 2364 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2365 .getMatchingRecipients(getContext(), addresses); 2366 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 2367 for (final RecipientChip temp : originalRecipients) { 2368 RecipientEntry entry = null; 2369 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2370 && getSpannable().getSpanStart(temp) != -1) { 2371 // Replace this. 2372 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 2373 .getDestination()))); 2374 } 2375 if (entry != null) { 2376 replacements.add(createFreeChip(entry)); 2377 } else { 2378 replacements.add(temp); 2379 } 2380 } 2381 if (replacements != null && replacements.size() > 0) { 2382 mHandler.post(new Runnable() { 2383 @Override 2384 public void run() { 2385 Editable oldText = getText(); 2386 int start, end; 2387 int i = 0; 2388 for (RecipientChip chip : originalRecipients) { 2389 // Find the location of the chip in the text currently shown. 2390 start = oldText.getSpanStart(chip); 2391 if (start != -1) { 2392 end = oldText.getSpanEnd(chip); 2393 oldText.removeSpan(chip); 2394 RecipientChip replacement = replacements.get(i); 2395 // Make sure we always have just 1 space at the 2396 // end to separate this chip from the next chip. 2397 SpannableString displayText = new SpannableString( 2398 createAddressText(replacement.getEntry()).trim() + " "); 2399 displayText.setSpan(replacement, 0, displayText.length()-1, 2400 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2401 // Replace the old text we found with with the new display text, 2402 // which now may also contain the display name of the recipient. 2403 oldText.replace(start, end, displayText); 2404 replacement.setOriginalText(displayText.toString()); 2405 } 2406 i++; 2407 } 2408 originalRecipients.clear(); 2409 } 2410 }); 2411 } 2412 return null; 2413 } 2414 } 2415 2416 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 2417 @SuppressWarnings("unchecked") 2418 @Override 2419 protected Void doInBackground(Object... params) { 2420 // For each chip in the list, look up the matching contact. 2421 // If there is a match, replace that chip with the matching 2422 // chip. 2423 final ArrayList<RecipientChip> originalRecipients = 2424 (ArrayList<RecipientChip>) params[0]; 2425 ArrayList<String> addresses = new ArrayList<String>(); 2426 RecipientChip chip; 2427 for (int i = 0; i < originalRecipients.size(); i++) { 2428 chip = originalRecipients.get(i); 2429 if (chip != null) { 2430 addresses.add(createAddressText(chip.getEntry())); 2431 } 2432 } 2433 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2434 .getMatchingRecipients(getContext(), addresses); 2435 for (final RecipientChip temp : originalRecipients) { 2436 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2437 && getSpannable().getSpanStart(temp) != -1) { 2438 // Replace this. 2439 RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress( 2440 temp.getEntry().getDestination()).toLowerCase())); 2441 // If we don't have a validated contact match, just use the 2442 // entry as it existed before. 2443 if (entry == null && !isPhoneQuery()) { 2444 entry = temp.getEntry(); 2445 } 2446 final RecipientEntry tempEntry = entry; 2447 if (tempEntry != null) { 2448 mHandler.post(new Runnable() { 2449 @Override 2450 public void run() { 2451 replaceChip(temp, tempEntry); 2452 } 2453 }); 2454 } 2455 } 2456 } 2457 return null; 2458 } 2459 } 2460 2461 2462 /** 2463 * MoreImageSpan is a simple class created for tracking the existence of a 2464 * more chip across activity restarts/ 2465 */ 2466 private class MoreImageSpan extends ImageSpan { 2467 public MoreImageSpan(Drawable b) { 2468 super(b); 2469 } 2470 } 2471 2472 @Override 2473 public boolean onDown(MotionEvent e) { 2474 return false; 2475 } 2476 2477 @Override 2478 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2479 // Do nothing. 2480 return false; 2481 } 2482 2483 @Override 2484 public void onLongPress(MotionEvent event) { 2485 if (mSelectedChip != null) { 2486 return; 2487 } 2488 float x = event.getX(); 2489 float y = event.getY(); 2490 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2491 RecipientChip currentChip = findChip(offset); 2492 if (currentChip != null) { 2493 if (mDragEnabled) { 2494 // Start drag-and-drop for the selected chip. 2495 startDrag(currentChip); 2496 } else { 2497 // Copy the selected chip email address. 2498 showCopyDialog(currentChip.getEntry().getDestination()); 2499 } 2500 } 2501 } 2502 2503 /** 2504 * Enables drag-and-drop for chips. 2505 */ 2506 public void enableDrag() { 2507 mDragEnabled = true; 2508 } 2509 2510 /** 2511 * Starts drag-and-drop for the selected chip. 2512 */ 2513 private void startDrag(RecipientChip currentChip) { 2514 String address = currentChip.getEntry().getDestination(); 2515 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA); 2516 2517 // Start drag mode. 2518 startDrag(data, new RecipientChipShadow(currentChip), null, 0); 2519 2520 // Remove the current chip, so drag-and-drop will result in a move. 2521 // TODO (phamm): consider readd this chip if it's dropped outside a target. 2522 removeChip(currentChip); 2523 } 2524 2525 /** 2526 * Handles drag event. 2527 */ 2528 @Override 2529 public boolean onDragEvent(DragEvent event) { 2530 switch (event.getAction()) { 2531 case DragEvent.ACTION_DRAG_STARTED: 2532 // Only handle plain text drag and drop. 2533 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); 2534 case DragEvent.ACTION_DRAG_ENTERED: 2535 requestFocus(); 2536 return true; 2537 case DragEvent.ACTION_DROP: 2538 handlePasteClip(event.getClipData()); 2539 return true; 2540 } 2541 return false; 2542 } 2543 2544 /** 2545 * Drag shadow for a {@link RecipientChip}. 2546 */ 2547 private final class RecipientChipShadow extends DragShadowBuilder { 2548 private final RecipientChip mChip; 2549 2550 public RecipientChipShadow(RecipientChip chip) { 2551 mChip = chip; 2552 } 2553 2554 @Override 2555 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 2556 Rect rect = mChip.getDrawable().getBounds(); 2557 shadowSize.set(rect.width(), rect.height()); 2558 shadowTouchPoint.set(rect.centerX(), rect.centerY()); 2559 } 2560 2561 @Override 2562 public void onDrawShadow(Canvas canvas) { 2563 mChip.getDrawable().draw(canvas); 2564 } 2565 } 2566 2567 private void showCopyDialog(final String address) { 2568 mCopyAddress = address; 2569 mCopyDialog.setTitle(address); 2570 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout); 2571 mCopyDialog.setCancelable(true); 2572 mCopyDialog.setCanceledOnTouchOutside(true); 2573 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1); 2574 button.setOnClickListener(this); 2575 int btnTitleId; 2576 if (isPhoneQuery()) { 2577 btnTitleId = R.string.copy_number; 2578 } else { 2579 btnTitleId = R.string.copy_email; 2580 } 2581 String buttonTitle = getContext().getResources().getString(btnTitleId); 2582 button.setText(buttonTitle); 2583 mCopyDialog.setOnDismissListener(this); 2584 mCopyDialog.show(); 2585 } 2586 2587 @Override 2588 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2589 // Do nothing. 2590 return false; 2591 } 2592 2593 @Override 2594 public void onShowPress(MotionEvent e) { 2595 // Do nothing. 2596 } 2597 2598 @Override 2599 public boolean onSingleTapUp(MotionEvent e) { 2600 // Do nothing. 2601 return false; 2602 } 2603 2604 @Override 2605 public void onDismiss(DialogInterface dialog) { 2606 mCopyAddress = null; 2607 } 2608 2609 @Override 2610 public void onClick(View v) { 2611 // Copy this to the clipboard. 2612 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2613 Context.CLIPBOARD_SERVICE); 2614 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2615 mCopyDialog.dismiss(); 2616 } 2617 2618 protected boolean isPhoneQuery() { 2619 return getAdapter() != null 2620 && ((BaseRecipientAdapter) getAdapter()).getQueryType() 2621 == BaseRecipientAdapter.QUERY_TYPE_PHONE; 2622 } 2623} 2624