RecipientEditTextView.java revision 5e60c2b9b39b0aec39e3a03f9a178c2cb857b9d6
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++; 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 if (whatEnd != getSelectionEnd()) { 1121 handleEdit(start, whatEnd); 1122 return true; 1123 } 1124 return commitChip(start, end , editable); 1125 } 1126 return false; 1127 } 1128 1129 private void commitByCharacter() { 1130 // We can't possibly commit by character if we can't tokenize. 1131 if (mTokenizer == null) { 1132 return; 1133 } 1134 Editable editable = getText(); 1135 int end = getSelectionEnd(); 1136 int start = mTokenizer.findTokenStart(editable, end); 1137 if (shouldCreateChip(start, end)) { 1138 commitChip(start, end, editable); 1139 } 1140 setSelection(getText().length()); 1141 } 1142 1143 private boolean commitChip(int start, int end, Editable editable) { 1144 ListAdapter adapter = getAdapter(); 1145 if (adapter != null && adapter.getCount() > 0 && enoughToFilter() 1146 && end == getSelectionEnd() && !isPhoneQuery()) { 1147 // choose the first entry. 1148 submitItemAtPosition(0); 1149 dismissDropDown(); 1150 return true; 1151 } else { 1152 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 1153 if (editable.length() > tokenEnd + 1) { 1154 char charAt = editable.charAt(tokenEnd + 1); 1155 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 1156 tokenEnd++; 1157 } 1158 } 1159 String text = editable.toString().substring(start, tokenEnd).trim(); 1160 clearComposingText(); 1161 if (text != null && text.length() > 0 && !text.equals(" ")) { 1162 RecipientEntry entry = createTokenizedEntry(text); 1163 if (entry != null) { 1164 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1165 CharSequence chipText = createChip(entry, false); 1166 if (chipText != null && start > -1 && end > -1) { 1167 editable.replace(start, end, chipText); 1168 } 1169 } 1170 // Only dismiss the dropdown if it is related to the text we 1171 // just committed. 1172 // For paste, it may not be as there are possibly multiple 1173 // tokens being added. 1174 if (end == getSelectionEnd()) { 1175 dismissDropDown(); 1176 } 1177 sanitizeBetween(); 1178 return true; 1179 } 1180 } 1181 return false; 1182 } 1183 1184 // Visible for testing. 1185 /* package */ void sanitizeBetween() { 1186 // Don't sanitize while we are waiting for content to chipify. 1187 if (mPendingChipsCount > 0) { 1188 return; 1189 } 1190 // Find the last chip. 1191 RecipientChip[] recips = getSortedRecipients(); 1192 if (recips != null && recips.length > 0) { 1193 RecipientChip last = recips[recips.length - 1]; 1194 RecipientChip beforeLast = null; 1195 if (recips.length > 1) { 1196 beforeLast = recips[recips.length - 2]; 1197 } 1198 int startLooking = 0; 1199 int end = getSpannable().getSpanStart(last); 1200 if (beforeLast != null) { 1201 startLooking = getSpannable().getSpanEnd(beforeLast); 1202 Editable text = getText(); 1203 if (startLooking == -1 || startLooking > text.length() - 1) { 1204 // There is nothing after this chip. 1205 return; 1206 } 1207 if (text.charAt(startLooking) == ' ') { 1208 startLooking++; 1209 } 1210 } 1211 if (startLooking >= 0 && end >= 0 && startLooking < end) { 1212 getText().delete(startLooking, end); 1213 } 1214 } 1215 } 1216 1217 private boolean shouldCreateChip(int start, int end) { 1218 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1219 } 1220 1221 private boolean alreadyHasChip(int start, int end) { 1222 if (mNoChips) { 1223 return true; 1224 } 1225 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 1226 if ((chips == null || chips.length == 0)) { 1227 return false; 1228 } 1229 return true; 1230 } 1231 1232 private void handleEdit(int start, int end) { 1233 if (start == -1 || end == -1) { 1234 // This chip no longer exists in the field. 1235 dismissDropDown(); 1236 return; 1237 } 1238 // This is in the middle of a chip, so select out the whole chip 1239 // and commit it. 1240 Editable editable = getText(); 1241 setSelection(end); 1242 String text = getText().toString().substring(start, end); 1243 if (!TextUtils.isEmpty(text)) { 1244 RecipientEntry entry = RecipientEntry.constructFakeEntry(text); 1245 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1246 CharSequence chipText = createChip(entry, false); 1247 int selEnd = getSelectionEnd(); 1248 if (chipText != null && start > -1 && selEnd > -1) { 1249 editable.replace(start, selEnd, chipText); 1250 } 1251 } 1252 dismissDropDown(); 1253 } 1254 1255 /** 1256 * If there is a selected chip, delegate the key events 1257 * to the selected chip. 1258 */ 1259 @Override 1260 public boolean onKeyDown(int keyCode, KeyEvent event) { 1261 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { 1262 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1263 mAlternatesPopup.dismiss(); 1264 } 1265 removeChip(mSelectedChip); 1266 } 1267 1268 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1269 return true; 1270 } 1271 1272 return super.onKeyDown(keyCode, event); 1273 } 1274 1275 // Visible for testing. 1276 /* package */ Spannable getSpannable() { 1277 return getText(); 1278 } 1279 1280 private int getChipStart(RecipientChip chip) { 1281 return getSpannable().getSpanStart(chip); 1282 } 1283 1284 private int getChipEnd(RecipientChip chip) { 1285 return getSpannable().getSpanEnd(chip); 1286 } 1287 1288 /** 1289 * Instead of filtering on the entire contents of the edit box, 1290 * this subclass method filters on the range from 1291 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1292 * if the length of that range meets or exceeds {@link #getThreshold} 1293 * and makes sure that the range is not already a Chip. 1294 */ 1295 @Override 1296 protected void performFiltering(CharSequence text, int keyCode) { 1297 if (enoughToFilter() && !isCompletedToken(text)) { 1298 int end = getSelectionEnd(); 1299 int start = mTokenizer.findTokenStart(text, end); 1300 // If this is a RecipientChip, don't filter 1301 // on its contents. 1302 Spannable span = getSpannable(); 1303 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1304 if (chips != null && chips.length > 0) { 1305 return; 1306 } 1307 } 1308 super.performFiltering(text, keyCode); 1309 } 1310 1311 // Visible for testing. 1312 /*package*/ boolean isCompletedToken(CharSequence text) { 1313 if (TextUtils.isEmpty(text)) { 1314 return false; 1315 } 1316 // Check to see if this is a completed token before filtering. 1317 int end = text.length(); 1318 int start = mTokenizer.findTokenStart(text, end); 1319 String token = text.toString().substring(start, end).trim(); 1320 if (!TextUtils.isEmpty(token)) { 1321 char atEnd = token.charAt(token.length() - 1); 1322 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON; 1323 } 1324 return false; 1325 } 1326 1327 private void clearSelectedChip() { 1328 if (mSelectedChip != null) { 1329 unselectChip(mSelectedChip); 1330 mSelectedChip = null; 1331 } 1332 setCursorVisible(true); 1333 } 1334 1335 /** 1336 * Monitor touch events in the RecipientEditTextView. 1337 * If the view does not have focus, any tap on the view 1338 * will just focus the view. If the view has focus, determine 1339 * if the touch target is a recipient chip. If it is and the chip 1340 * is not selected, select it and clear any other selected chips. 1341 * If it isn't, then select that chip. 1342 */ 1343 @Override 1344 public boolean onTouchEvent(MotionEvent event) { 1345 if (!isFocused()) { 1346 // Ignore any chip taps until this view is focused. 1347 return super.onTouchEvent(event); 1348 } 1349 boolean handled = super.onTouchEvent(event); 1350 int action = event.getAction(); 1351 boolean chipWasSelected = false; 1352 if (mSelectedChip == null) { 1353 mGestureDetector.onTouchEvent(event); 1354 } 1355 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1356 float x = event.getX(); 1357 float y = event.getY(); 1358 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1359 RecipientChip currentChip = findChip(offset); 1360 if (currentChip != null) { 1361 if (action == MotionEvent.ACTION_UP) { 1362 if (mSelectedChip != null && mSelectedChip != currentChip) { 1363 clearSelectedChip(); 1364 mSelectedChip = selectChip(currentChip); 1365 } else if (mSelectedChip == null) { 1366 setSelection(getText().length()); 1367 commitDefault(); 1368 mSelectedChip = selectChip(currentChip); 1369 } else { 1370 onClick(mSelectedChip, offset, x, y); 1371 } 1372 } 1373 chipWasSelected = true; 1374 handled = true; 1375 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) { 1376 chipWasSelected = true; 1377 } 1378 } 1379 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1380 clearSelectedChip(); 1381 } 1382 return handled; 1383 } 1384 1385 private void scrollLineIntoView(int line) { 1386 if (mScrollView != null) { 1387 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1388 } 1389 } 1390 1391 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1392 int width, Context context) { 1393 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1394 int bottom; 1395 if (line == getLineCount() -1) { 1396 bottom = 0; 1397 } else { 1398 bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1 1399 - line))); 1400 } 1401 // Align the alternates popup with the left side of the View, 1402 // regardless of the position of the chip tapped. 1403 alternatesPopup.setWidth(width); 1404 alternatesPopup.setAnchorView(this); 1405 alternatesPopup.setVerticalOffset(bottom); 1406 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1407 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1408 // Clear the checked item. 1409 mCheckedItem = -1; 1410 alternatesPopup.show(); 1411 ListView listView = alternatesPopup.getListView(); 1412 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1413 // Checked item would be -1 if the adapter has not 1414 // loaded the view that should be checked yet. The 1415 // variable will be set correctly when onCheckedItemChanged 1416 // is called in a separate thread. 1417 if (mCheckedItem != -1) { 1418 listView.setItemChecked(mCheckedItem, true); 1419 mCheckedItem = -1; 1420 } 1421 } 1422 1423 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1424 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1425 mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this); 1426 } 1427 1428 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1429 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1430 .getEntry()); 1431 } 1432 1433 @Override 1434 public void onCheckedItemChanged(int position) { 1435 ListView listView = mAlternatesPopup.getListView(); 1436 if (listView != null && listView.getCheckedItemCount() == 0) { 1437 listView.setItemChecked(position, true); 1438 } 1439 mCheckedItem = position; 1440 } 1441 1442 // TODO: This algorithm will need a lot of tweaking after more people have used 1443 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1444 // what comes before the finger. 1445 private int putOffsetInRange(int o) { 1446 int offset = o; 1447 Editable text = getText(); 1448 int length = text.length(); 1449 // Remove whitespace from end to find "real end" 1450 int realLength = length; 1451 for (int i = length - 1; i >= 0; i--) { 1452 if (text.charAt(i) == ' ') { 1453 realLength--; 1454 } else { 1455 break; 1456 } 1457 } 1458 1459 // If the offset is beyond or at the end of the text, 1460 // leave it alone. 1461 if (offset >= realLength) { 1462 return offset; 1463 } 1464 Editable editable = getText(); 1465 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1466 // Keep walking backward! 1467 offset--; 1468 } 1469 return offset; 1470 } 1471 1472 private int findText(Editable text, int offset) { 1473 if (text.charAt(offset) != ' ') { 1474 return offset; 1475 } 1476 return -1; 1477 } 1478 1479 private RecipientChip findChip(int offset) { 1480 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1481 // Find the chip that contains this offset. 1482 for (int i = 0; i < chips.length; i++) { 1483 RecipientChip chip = chips[i]; 1484 int start = getChipStart(chip); 1485 int end = getChipEnd(chip); 1486 if (offset >= start && offset <= end) { 1487 return chip; 1488 } 1489 } 1490 return null; 1491 } 1492 1493 // Visible for testing. 1494 // Use this method to generate text to add to the list of addresses. 1495 /* package */String createAddressText(RecipientEntry entry) { 1496 String display = entry.getDisplayName(); 1497 String address = entry.getDestination(); 1498 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1499 display = null; 1500 } 1501 String trimmedDisplayText; 1502 if (isPhoneQuery() && isPhoneNumber(address)) { 1503 trimmedDisplayText = address.trim(); 1504 } else { 1505 if (address != null) { 1506 // Tokenize out the address in case the address already 1507 // contained the username as well. 1508 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1509 if (tokenized != null && tokenized.length > 0) { 1510 address = tokenized[0].getAddress(); 1511 } 1512 } 1513 Rfc822Token token = new Rfc822Token(display, address, null); 1514 trimmedDisplayText = token.toString().trim(); 1515 } 1516 int index = trimmedDisplayText.indexOf(","); 1517 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText) 1518 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1519 .terminateToken(trimmedDisplayText) : trimmedDisplayText; 1520 } 1521 1522 // Visible for testing. 1523 // Use this method to generate text to display in a chip. 1524 /*package*/ String createChipDisplayText(RecipientEntry entry) { 1525 String display = entry.getDisplayName(); 1526 String address = entry.getDestination(); 1527 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1528 display = null; 1529 } 1530 if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) { 1531 // Tokenize out the address in case the address already 1532 // contained the username as well. 1533 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1534 if (tokenized != null && tokenized.length > 0) { 1535 address = tokenized[0].getAddress(); 1536 } 1537 } 1538 if (!TextUtils.isEmpty(display)) { 1539 return display; 1540 } else if (!TextUtils.isEmpty(address)){ 1541 return address; 1542 } else { 1543 return new Rfc822Token(display, address, null).toString(); 1544 } 1545 } 1546 1547 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1548 String displayText = createAddressText(entry); 1549 if (TextUtils.isEmpty(displayText)) { 1550 return null; 1551 } 1552 SpannableString chipText = null; 1553 // Always leave a blank space at the end of a chip. 1554 int end = getSelectionEnd(); 1555 int start = mTokenizer.findTokenStart(getText(), end); 1556 int textLength = displayText.length()-1; 1557 chipText = new SpannableString(displayText); 1558 if (!mNoChips) { 1559 try { 1560 RecipientChip chip = constructChipSpan(entry, start, pressed, 1561 false /* leave space for contact icon */); 1562 chipText.setSpan(chip, 0, textLength, 1563 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1564 chip.setOriginalText(chipText.toString()); 1565 } catch (NullPointerException e) { 1566 Log.e(TAG, e.getMessage(), e); 1567 return null; 1568 } 1569 } 1570 return chipText; 1571 } 1572 1573 /** 1574 * When an item in the suggestions list has been clicked, create a chip from the 1575 * contact information of the selected item. 1576 */ 1577 @Override 1578 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1579 submitItemAtPosition(position); 1580 } 1581 1582 private void submitItemAtPosition(int position) { 1583 RecipientEntry entry = createValidatedEntry( 1584 (RecipientEntry)getAdapter().getItem(position)); 1585 if (entry == null) { 1586 return; 1587 } 1588 clearComposingText(); 1589 1590 int end = getSelectionEnd(); 1591 int start = mTokenizer.findTokenStart(getText(), end); 1592 1593 Editable editable = getText(); 1594 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1595 CharSequence chip = createChip(entry, false); 1596 if (chip != null && start >= 0 && end >= 0) { 1597 editable.replace(start, end, chip); 1598 } 1599 sanitizeBetween(); 1600 } 1601 1602 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1603 if (item == null) { 1604 return null; 1605 } 1606 final RecipientEntry entry; 1607 // If the display name and the address are the same, or if this is a 1608 // valid contact, but the destination is invalid, then make this a fake 1609 // recipient that is editable. 1610 String destination = item.getDestination(); 1611 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1612 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(), 1613 destination); 1614 } else if (RecipientEntry.isCreatedRecipient(item.getContactId()) 1615 && (TextUtils.isEmpty(item.getDisplayName()) 1616 || TextUtils.equals(item.getDisplayName(), destination) 1617 || (mValidator != null && !mValidator.isValid(destination)))) { 1618 entry = RecipientEntry.constructFakeEntry(destination); 1619 } else { 1620 entry = item; 1621 } 1622 return entry; 1623 } 1624 1625 /** Returns a collection of contact Id for each chip inside this View. */ 1626 /* package */ Collection<Long> getContactIds() { 1627 final Set<Long> result = new HashSet<Long>(); 1628 RecipientChip[] chips = getSortedRecipients(); 1629 if (chips != null) { 1630 for (RecipientChip chip : chips) { 1631 result.add(chip.getContactId()); 1632 } 1633 } 1634 return result; 1635 } 1636 1637 1638 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1639 /* package */ Collection<Long> getDataIds() { 1640 final Set<Long> result = new HashSet<Long>(); 1641 RecipientChip [] chips = getSortedRecipients(); 1642 if (chips != null) { 1643 for (RecipientChip chip : chips) { 1644 result.add(chip.getDataId()); 1645 } 1646 } 1647 return result; 1648 } 1649 1650 // Visible for testing. 1651 /* package */RecipientChip[] getSortedRecipients() { 1652 RecipientChip[] recips = getSpannable() 1653 .getSpans(0, getText().length(), RecipientChip.class); 1654 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1655 .asList(recips)); 1656 final Spannable spannable = getSpannable(); 1657 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1658 1659 @Override 1660 public int compare(RecipientChip first, RecipientChip second) { 1661 int firstStart = spannable.getSpanStart(first); 1662 int secondStart = spannable.getSpanStart(second); 1663 if (firstStart < secondStart) { 1664 return -1; 1665 } else if (firstStart > secondStart) { 1666 return 1; 1667 } else { 1668 return 0; 1669 } 1670 } 1671 }); 1672 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1673 } 1674 1675 @Override 1676 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1677 return false; 1678 } 1679 1680 @Override 1681 public void onDestroyActionMode(ActionMode mode) { 1682 } 1683 1684 @Override 1685 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1686 return false; 1687 } 1688 1689 /** 1690 * No chips are selectable. 1691 */ 1692 @Override 1693 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1694 return false; 1695 } 1696 1697 // Visible for testing. 1698 /* package */ImageSpan getMoreChip() { 1699 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1700 MoreImageSpan.class); 1701 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1702 } 1703 1704 private MoreImageSpan createMoreSpan(int count) { 1705 String moreText = String.format(mMoreItem.getText().toString(), count); 1706 TextPaint morePaint = new TextPaint(getPaint()); 1707 morePaint.setTextSize(mMoreItem.getTextSize()); 1708 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1709 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1710 + mMoreItem.getPaddingRight(); 1711 int height = getLineHeight(); 1712 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1713 Canvas canvas = new Canvas(drawable); 1714 int adjustedHeight = height; 1715 Layout layout = getLayout(); 1716 if (layout != null) { 1717 adjustedHeight -= layout.getLineDescent(0); 1718 } 1719 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1720 1721 Drawable result = new BitmapDrawable(getResources(), drawable); 1722 result.setBounds(0, 0, width, height); 1723 return new MoreImageSpan(result); 1724 } 1725 1726 // Visible for testing. 1727 /*package*/ void createMoreChipPlainText() { 1728 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one. 1729 Editable text = getText(); 1730 int start = 0; 1731 int end = start; 1732 for (int i = 0; i < CHIP_LIMIT; i++) { 1733 end = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1734 start = end; // move to the next token and get its end. 1735 } 1736 // Now, count total addresses. 1737 start = 0; 1738 int tokenCount = countTokens(text); 1739 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT); 1740 SpannableString chipText = new SpannableString(text.subSequence(end, text.length())); 1741 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1742 text.replace(end, text.length(), chipText); 1743 mMoreChip = moreSpan; 1744 } 1745 1746 // Visible for testing. 1747 /* package */int countTokens(Editable text) { 1748 int tokenCount = 0; 1749 int start = 0; 1750 while (start < text.length()) { 1751 start = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1752 tokenCount++; 1753 if (start >= text.length()) { 1754 break; 1755 } 1756 } 1757 return tokenCount; 1758 } 1759 1760 /** 1761 * Create the more chip. The more chip is text that replaces any chips that 1762 * do not fit in the pre-defined available space when the 1763 * RecipientEditTextView loses focus. 1764 */ 1765 // Visible for testing. 1766 /* package */ void createMoreChip() { 1767 if (mNoChips) { 1768 createMoreChipPlainText(); 1769 return; 1770 } 1771 1772 if (!mShouldShrink) { 1773 return; 1774 } 1775 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1776 if (tempMore.length > 0) { 1777 getSpannable().removeSpan(tempMore[0]); 1778 } 1779 RecipientChip[] recipients = getSortedRecipients(); 1780 1781 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1782 mMoreChip = null; 1783 return; 1784 } 1785 Spannable spannable = getSpannable(); 1786 int numRecipients = recipients.length; 1787 int overage = numRecipients - CHIP_LIMIT; 1788 MoreImageSpan moreSpan = createMoreSpan(overage); 1789 mRemovedSpans = new ArrayList<RecipientChip>(); 1790 int totalReplaceStart = 0; 1791 int totalReplaceEnd = 0; 1792 Editable text = getText(); 1793 for (int i = numRecipients - overage; i < recipients.length; i++) { 1794 mRemovedSpans.add(recipients[i]); 1795 if (i == numRecipients - overage) { 1796 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1797 } 1798 if (i == recipients.length - 1) { 1799 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1800 } 1801 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1802 int spanStart = spannable.getSpanStart(recipients[i]); 1803 int spanEnd = spannable.getSpanEnd(recipients[i]); 1804 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1805 } 1806 spannable.removeSpan(recipients[i]); 1807 } 1808 if (totalReplaceEnd < text.length()) { 1809 totalReplaceEnd = text.length(); 1810 } 1811 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1812 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1813 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1814 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1815 text.replace(start, end, chipText); 1816 mMoreChip = moreSpan; 1817 // If adding the +more chip goes over the limit, resize accordingly. 1818 if (!isPhoneQuery() && getLineCount() > mMaxLines) { 1819 setMaxLines(getLineCount()); 1820 } 1821 } 1822 1823 /** 1824 * Replace the more chip, if it exists, with all of the recipient chips it had 1825 * replaced when the RecipientEditTextView gains focus. 1826 */ 1827 // Visible for testing. 1828 /*package*/ void removeMoreChip() { 1829 if (mMoreChip != null) { 1830 Spannable span = getSpannable(); 1831 span.removeSpan(mMoreChip); 1832 mMoreChip = null; 1833 // Re-add the spans that were removed. 1834 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1835 // Recreate each removed span. 1836 RecipientChip[] recipients = getSortedRecipients(); 1837 // Start the search for tokens after the last currently visible 1838 // chip. 1839 if (recipients == null || recipients.length == 0) { 1840 return; 1841 } 1842 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1843 Editable editable = getText(); 1844 for (RecipientChip chip : mRemovedSpans) { 1845 int chipStart; 1846 int chipEnd; 1847 String token; 1848 // Need to find the location of the chip, again. 1849 token = (String) chip.getOriginalText(); 1850 // As we find the matching recipient for the remove spans, 1851 // reduce the size of the string we need to search. 1852 // That way, if there are duplicates, we always find the correct 1853 // recipient. 1854 chipStart = editable.toString().indexOf(token, end); 1855 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1856 // Only set the span if we found a matching token. 1857 if (chipStart != -1) { 1858 editable.setSpan(chip, chipStart, chipEnd, 1859 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1860 } 1861 } 1862 mRemovedSpans.clear(); 1863 } 1864 } 1865 } 1866 1867 /** 1868 * Show specified chip as selected. If the RecipientChip is just an email address, 1869 * selecting the chip will take the contents of the chip and place it at 1870 * the end of the RecipientEditTextView for inline editing. If the 1871 * RecipientChip is a complete contact, then selecting the chip 1872 * will change the background color of the chip, show the delete icon, 1873 * and a popup window with the address in use highlighted and any other 1874 * alternate addresses for the contact. 1875 * @param currentChip Chip to select. 1876 * @return A RecipientChip in the selected state or null if the chip 1877 * just contained an email address. 1878 */ 1879 private RecipientChip selectChip(RecipientChip currentChip) { 1880 if (shouldShowEditableText(currentChip)) { 1881 CharSequence text = currentChip.getValue(); 1882 Editable editable = getText(); 1883 removeChip(currentChip); 1884 editable.append(text); 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