RecipientEditTextView.java revision 637ac7db04071a04c5b3e4755ba9ad4cac64f2f1
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 RecipientChip chip = null; 900 try { 901 if (!mNoChips) { 902 /* leave space for the contact icon if this is not just an email address */ 903 chip = constructChipSpan( 904 entry, 905 tokenStart, 906 false, 907 TextUtils.isEmpty(entry.getDisplayName()) 908 || TextUtils.equals(entry.getDisplayName(), 909 entry.getDestination())); 910 } 911 } catch (NullPointerException e) { 912 Log.e(TAG, e.getMessage(), e); 913 } 914 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 915 // Add this chip to the list of entries "to replace" 916 if (chip != null) { 917 if (mTemporaryRecipients == null) { 918 mTemporaryRecipients = new ArrayList<RecipientChip>(); 919 } 920 chip.setOriginalText(chipText.toString()); 921 mTemporaryRecipients.add(chip); 922 } 923 } 924 } 925 926 private static boolean isPhoneNumber(String number) { 927 // TODO: replace this function with libphonenumber's isPossibleNumber (see 928 // PhoneNumberUtil). One complication is that it requires the sender's region which 929 // comes from the CurrentCountryIso. For now, let's just do this simple match. 930 if (TextUtils.isEmpty(number)) { 931 return false; 932 } 933 934 Matcher match = Patterns.PHONE.matcher(number); 935 return match.matches(); 936 } 937 938 private RecipientEntry createTokenizedEntry(String token) { 939 if (TextUtils.isEmpty(token)) { 940 return null; 941 } 942 if (isPhoneQuery() && isPhoneNumber(token)) { 943 return RecipientEntry.constructFakeEntry(token, true); 944 } 945 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 946 String display = null; 947 boolean isValid = isValid(token); 948 if (isValid && tokens != null && tokens.length > 0) { 949 // If we can get a name from tokenizing, then generate an entry from 950 // this. 951 display = tokens[0].getName(); 952 if (!TextUtils.isEmpty(display)) { 953 if (!isPhoneQuery()) { 954 if (!TextUtils.isEmpty(token)) { 955 token = token.trim(); 956 } 957 char charAt = token.charAt(token.length() - 1); 958 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 959 token = token.substring(0, token.length() - 1); 960 } 961 } 962 return RecipientEntry.constructGeneratedEntry(display, token, isValid); 963 } else { 964 display = tokens[0].getAddress(); 965 if (!TextUtils.isEmpty(display)) { 966 return RecipientEntry.constructFakeEntry(display, isValid); 967 } 968 } 969 } 970 // Unable to validate the token or to create a valid token from it. 971 // Just create a chip the user can edit. 972 String validatedToken = null; 973 if (mValidator != null && !isValid) { 974 // Try fixing up the entry using the validator. 975 validatedToken = mValidator.fixText(token).toString(); 976 if (!TextUtils.isEmpty(validatedToken)) { 977 if (validatedToken.contains(token)) { 978 // protect against the case of a validator with a null 979 // domain, 980 // which doesn't add a domain to the token 981 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 982 if (tokenized.length > 0) { 983 validatedToken = tokenized[0].getAddress(); 984 isValid = true; 985 } 986 } else { 987 // We ran into a case where the token was invalid and 988 // removed 989 // by the validator. In this case, just use the original 990 // token 991 // and let the user sort out the error chip. 992 validatedToken = null; 993 isValid = false; 994 } 995 } 996 } 997 // Otherwise, fallback to just creating an editable email address chip. 998 return RecipientEntry.constructFakeEntry( 999 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid); 1000 } 1001 1002 private boolean isValid(String text) { 1003 return mValidator == null ? true : mValidator.isValid(text); 1004 } 1005 1006 private String tokenizeAddress(String destination) { 1007 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); 1008 if (tokens != null && tokens.length > 0) { 1009 return tokens[0].getAddress(); 1010 } 1011 return destination; 1012 } 1013 1014 @Override 1015 public void setTokenizer(Tokenizer tokenizer) { 1016 mTokenizer = tokenizer; 1017 super.setTokenizer(mTokenizer); 1018 } 1019 1020 @Override 1021 public void setValidator(Validator validator) { 1022 mValidator = validator; 1023 super.setValidator(validator); 1024 } 1025 1026 /** 1027 * We cannot use the default mechanism for replaceText. Instead, 1028 * we override onItemClickListener so we can get all the associated 1029 * contact information including display text, address, and id. 1030 */ 1031 @Override 1032 protected void replaceText(CharSequence text) { 1033 return; 1034 } 1035 1036 /** 1037 * Dismiss any selected chips when the back key is pressed. 1038 */ 1039 @Override 1040 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 1041 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) { 1042 clearSelectedChip(); 1043 return true; 1044 } 1045 return super.onKeyPreIme(keyCode, event); 1046 } 1047 1048 /** 1049 * Monitor key presses in this view to see if the user types 1050 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. 1051 * If the user has entered text that has contact matches and types 1052 * a commit key, create a chip from the topmost matching contact. 1053 * If the user has entered text that has no contact matches and types 1054 * a commit key, then create a chip from the text they have entered. 1055 */ 1056 @Override 1057 public boolean onKeyUp(int keyCode, KeyEvent event) { 1058 switch (keyCode) { 1059 case KeyEvent.KEYCODE_ENTER: 1060 case KeyEvent.KEYCODE_DPAD_CENTER: 1061 if (event.hasNoModifiers()) { 1062 if (commitDefault()) { 1063 return true; 1064 } 1065 if (mSelectedChip != null) { 1066 clearSelectedChip(); 1067 return true; 1068 } else if (focusNext()) { 1069 return true; 1070 } 1071 } 1072 break; 1073 case KeyEvent.KEYCODE_TAB: 1074 if (event.hasNoModifiers()) { 1075 if (mSelectedChip != null) { 1076 clearSelectedChip(); 1077 } else { 1078 commitDefault(); 1079 } 1080 if (focusNext()) { 1081 return true; 1082 } 1083 } 1084 break; 1085 } 1086 return super.onKeyUp(keyCode, event); 1087 } 1088 1089 private boolean focusNext() { 1090 View next = focusSearch(View.FOCUS_DOWN); 1091 if (next != null) { 1092 next.requestFocus(); 1093 return true; 1094 } 1095 return false; 1096 } 1097 1098 /** 1099 * Create a chip from the default selection. If the popup is showing, the 1100 * default is the first item in the popup suggestions list. Otherwise, it is 1101 * whatever the user had typed in. End represents where the the tokenizer 1102 * should search for a token to turn into a chip. 1103 * @return If a chip was created from a real contact. 1104 */ 1105 private boolean commitDefault() { 1106 // If there is no tokenizer, don't try to commit. 1107 if (mTokenizer == null) { 1108 return false; 1109 } 1110 Editable editable = getText(); 1111 int end = getSelectionEnd(); 1112 int start = mTokenizer.findTokenStart(editable, end); 1113 1114 if (shouldCreateChip(start, end)) { 1115 int whatEnd = mTokenizer.findTokenEnd(getText(), start); 1116 // In the middle of chip; treat this as an edit 1117 // and commit the whole token. 1118 whatEnd = movePastTerminators(whatEnd); 1119 if (whatEnd != getSelectionEnd()) { 1120 handleEdit(start, whatEnd); 1121 return true; 1122 } 1123 return commitChip(start, end , editable); 1124 } 1125 return false; 1126 } 1127 1128 private void commitByCharacter() { 1129 // We can't possibly commit by character if we can't tokenize. 1130 if (mTokenizer == null) { 1131 return; 1132 } 1133 Editable editable = getText(); 1134 int end = getSelectionEnd(); 1135 int start = mTokenizer.findTokenStart(editable, end); 1136 if (shouldCreateChip(start, end)) { 1137 commitChip(start, end, editable); 1138 } 1139 setSelection(getText().length()); 1140 } 1141 1142 private boolean commitChip(int start, int end, Editable editable) { 1143 ListAdapter adapter = getAdapter(); 1144 if (adapter != null && adapter.getCount() > 0 && enoughToFilter() 1145 && end == getSelectionEnd() && !isPhoneQuery()) { 1146 // choose the first entry. 1147 submitItemAtPosition(0); 1148 dismissDropDown(); 1149 return true; 1150 } else { 1151 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 1152 if (editable.length() > tokenEnd + 1) { 1153 char charAt = editable.charAt(tokenEnd + 1); 1154 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 1155 tokenEnd++; 1156 } 1157 } 1158 String text = editable.toString().substring(start, tokenEnd).trim(); 1159 clearComposingText(); 1160 if (text != null && text.length() > 0 && !text.equals(" ")) { 1161 RecipientEntry entry = createTokenizedEntry(text); 1162 if (entry != null) { 1163 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1164 CharSequence chipText = createChip(entry, false); 1165 if (chipText != null && start > -1 && end > -1) { 1166 editable.replace(start, end, chipText); 1167 } 1168 } 1169 // Only dismiss the dropdown if it is related to the text we 1170 // just committed. 1171 // For paste, it may not be as there are possibly multiple 1172 // tokens being added. 1173 if (end == getSelectionEnd()) { 1174 dismissDropDown(); 1175 } 1176 sanitizeBetween(); 1177 return true; 1178 } 1179 } 1180 return false; 1181 } 1182 1183 // Visible for testing. 1184 /* package */ void sanitizeBetween() { 1185 // Don't sanitize while we are waiting for content to chipify. 1186 if (mPendingChipsCount > 0) { 1187 return; 1188 } 1189 // Find the last chip. 1190 RecipientChip[] recips = getSortedRecipients(); 1191 if (recips != null && recips.length > 0) { 1192 RecipientChip last = recips[recips.length - 1]; 1193 RecipientChip beforeLast = null; 1194 if (recips.length > 1) { 1195 beforeLast = recips[recips.length - 2]; 1196 } 1197 int startLooking = 0; 1198 int end = getSpannable().getSpanStart(last); 1199 if (beforeLast != null) { 1200 startLooking = getSpannable().getSpanEnd(beforeLast); 1201 Editable text = getText(); 1202 if (startLooking == -1 || startLooking > text.length() - 1) { 1203 // There is nothing after this chip. 1204 return; 1205 } 1206 if (text.charAt(startLooking) == ' ') { 1207 startLooking++; 1208 } 1209 } 1210 if (startLooking >= 0 && end >= 0 && startLooking < end) { 1211 getText().delete(startLooking, end); 1212 } 1213 } 1214 } 1215 1216 private boolean shouldCreateChip(int start, int end) { 1217 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1218 } 1219 1220 private boolean alreadyHasChip(int start, int end) { 1221 if (mNoChips) { 1222 return true; 1223 } 1224 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 1225 if ((chips == null || chips.length == 0)) { 1226 return false; 1227 } 1228 return true; 1229 } 1230 1231 private void handleEdit(int start, int end) { 1232 if (start == -1 || end == -1) { 1233 // This chip no longer exists in the field. 1234 dismissDropDown(); 1235 return; 1236 } 1237 // This is in the middle of a chip, so select out the whole chip 1238 // and commit it. 1239 Editable editable = getText(); 1240 setSelection(end); 1241 String text = getText().toString().substring(start, end); 1242 if (!TextUtils.isEmpty(text)) { 1243 RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text)); 1244 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1245 CharSequence chipText = createChip(entry, false); 1246 int selEnd = getSelectionEnd(); 1247 if (chipText != null && start > -1 && selEnd > -1) { 1248 editable.replace(start, selEnd, chipText); 1249 } 1250 } 1251 dismissDropDown(); 1252 } 1253 1254 /** 1255 * If there is a selected chip, delegate the key events 1256 * to the selected chip. 1257 */ 1258 @Override 1259 public boolean onKeyDown(int keyCode, KeyEvent event) { 1260 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { 1261 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1262 mAlternatesPopup.dismiss(); 1263 } 1264 removeChip(mSelectedChip); 1265 } 1266 1267 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1268 return true; 1269 } 1270 1271 return super.onKeyDown(keyCode, event); 1272 } 1273 1274 // Visible for testing. 1275 /* package */ Spannable getSpannable() { 1276 return getText(); 1277 } 1278 1279 private int getChipStart(RecipientChip chip) { 1280 return getSpannable().getSpanStart(chip); 1281 } 1282 1283 private int getChipEnd(RecipientChip chip) { 1284 return getSpannable().getSpanEnd(chip); 1285 } 1286 1287 /** 1288 * Instead of filtering on the entire contents of the edit box, 1289 * this subclass method filters on the range from 1290 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1291 * if the length of that range meets or exceeds {@link #getThreshold} 1292 * and makes sure that the range is not already a Chip. 1293 */ 1294 @Override 1295 protected void performFiltering(CharSequence text, int keyCode) { 1296 if (enoughToFilter() && !isCompletedToken(text)) { 1297 int end = getSelectionEnd(); 1298 int start = mTokenizer.findTokenStart(text, end); 1299 // If this is a RecipientChip, don't filter 1300 // on its contents. 1301 Spannable span = getSpannable(); 1302 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1303 if (chips != null && chips.length > 0) { 1304 return; 1305 } 1306 } 1307 super.performFiltering(text, keyCode); 1308 } 1309 1310 // Visible for testing. 1311 /*package*/ boolean isCompletedToken(CharSequence text) { 1312 if (TextUtils.isEmpty(text)) { 1313 return false; 1314 } 1315 // Check to see if this is a completed token before filtering. 1316 int end = text.length(); 1317 int start = mTokenizer.findTokenStart(text, end); 1318 String token = text.toString().substring(start, end).trim(); 1319 if (!TextUtils.isEmpty(token)) { 1320 char atEnd = token.charAt(token.length() - 1); 1321 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON; 1322 } 1323 return false; 1324 } 1325 1326 private void clearSelectedChip() { 1327 if (mSelectedChip != null) { 1328 unselectChip(mSelectedChip); 1329 mSelectedChip = null; 1330 } 1331 setCursorVisible(true); 1332 } 1333 1334 /** 1335 * Monitor touch events in the RecipientEditTextView. 1336 * If the view does not have focus, any tap on the view 1337 * will just focus the view. If the view has focus, determine 1338 * if the touch target is a recipient chip. If it is and the chip 1339 * is not selected, select it and clear any other selected chips. 1340 * If it isn't, then select that chip. 1341 */ 1342 @Override 1343 public boolean onTouchEvent(MotionEvent event) { 1344 if (!isFocused()) { 1345 // Ignore any chip taps until this view is focused. 1346 return super.onTouchEvent(event); 1347 } 1348 boolean handled = super.onTouchEvent(event); 1349 int action = event.getAction(); 1350 boolean chipWasSelected = false; 1351 if (mSelectedChip == null) { 1352 mGestureDetector.onTouchEvent(event); 1353 } 1354 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1355 float x = event.getX(); 1356 float y = event.getY(); 1357 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1358 RecipientChip currentChip = findChip(offset); 1359 if (currentChip != null) { 1360 if (action == MotionEvent.ACTION_UP) { 1361 if (mSelectedChip != null && mSelectedChip != currentChip) { 1362 clearSelectedChip(); 1363 mSelectedChip = selectChip(currentChip); 1364 } else if (mSelectedChip == null) { 1365 setSelection(getText().length()); 1366 commitDefault(); 1367 mSelectedChip = selectChip(currentChip); 1368 } else { 1369 onClick(mSelectedChip, offset, x, y); 1370 } 1371 } 1372 chipWasSelected = true; 1373 handled = true; 1374 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) { 1375 chipWasSelected = true; 1376 } 1377 } 1378 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1379 clearSelectedChip(); 1380 } 1381 return handled; 1382 } 1383 1384 private void scrollLineIntoView(int line) { 1385 if (mScrollView != null) { 1386 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1387 } 1388 } 1389 1390 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1391 int width, Context context) { 1392 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1393 int bottom; 1394 if (line == getLineCount() -1) { 1395 bottom = 0; 1396 } else { 1397 bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1 1398 - line))); 1399 } 1400 // Align the alternates popup with the left side of the View, 1401 // regardless of the position of the chip tapped. 1402 alternatesPopup.setWidth(width); 1403 alternatesPopup.setAnchorView(this); 1404 alternatesPopup.setVerticalOffset(bottom); 1405 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1406 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1407 // Clear the checked item. 1408 mCheckedItem = -1; 1409 alternatesPopup.show(); 1410 ListView listView = alternatesPopup.getListView(); 1411 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1412 // Checked item would be -1 if the adapter has not 1413 // loaded the view that should be checked yet. The 1414 // variable will be set correctly when onCheckedItemChanged 1415 // is called in a separate thread. 1416 if (mCheckedItem != -1) { 1417 listView.setItemChecked(mCheckedItem, true); 1418 mCheckedItem = -1; 1419 } 1420 } 1421 1422 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1423 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1424 mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this); 1425 } 1426 1427 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1428 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1429 .getEntry()); 1430 } 1431 1432 @Override 1433 public void onCheckedItemChanged(int position) { 1434 ListView listView = mAlternatesPopup.getListView(); 1435 if (listView != null && listView.getCheckedItemCount() == 0) { 1436 listView.setItemChecked(position, true); 1437 } 1438 mCheckedItem = position; 1439 } 1440 1441 // TODO: This algorithm will need a lot of tweaking after more people have used 1442 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1443 // what comes before the finger. 1444 private int putOffsetInRange(int o) { 1445 int offset = o; 1446 Editable text = getText(); 1447 int length = text.length(); 1448 // Remove whitespace from end to find "real end" 1449 int realLength = length; 1450 for (int i = length - 1; i >= 0; i--) { 1451 if (text.charAt(i) == ' ') { 1452 realLength--; 1453 } else { 1454 break; 1455 } 1456 } 1457 1458 // If the offset is beyond or at the end of the text, 1459 // leave it alone. 1460 if (offset >= realLength) { 1461 return offset; 1462 } 1463 Editable editable = getText(); 1464 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1465 // Keep walking backward! 1466 offset--; 1467 } 1468 return offset; 1469 } 1470 1471 private int findText(Editable text, int offset) { 1472 if (text.charAt(offset) != ' ') { 1473 return offset; 1474 } 1475 return -1; 1476 } 1477 1478 private RecipientChip findChip(int offset) { 1479 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1480 // Find the chip that contains this offset. 1481 for (int i = 0; i < chips.length; i++) { 1482 RecipientChip chip = chips[i]; 1483 int start = getChipStart(chip); 1484 int end = getChipEnd(chip); 1485 if (offset >= start && offset <= end) { 1486 return chip; 1487 } 1488 } 1489 return null; 1490 } 1491 1492 // Visible for testing. 1493 // Use this method to generate text to add to the list of addresses. 1494 /* package */String createAddressText(RecipientEntry entry) { 1495 String display = entry.getDisplayName(); 1496 String address = entry.getDestination(); 1497 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1498 display = null; 1499 } 1500 String trimmedDisplayText; 1501 if (isPhoneQuery() && isPhoneNumber(address)) { 1502 trimmedDisplayText = address.trim(); 1503 } else { 1504 if (address != null) { 1505 // Tokenize out the address in case the address already 1506 // contained the username as well. 1507 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1508 if (tokenized != null && tokenized.length > 0) { 1509 address = tokenized[0].getAddress(); 1510 } 1511 } 1512 Rfc822Token token = new Rfc822Token(display, address, null); 1513 trimmedDisplayText = token.toString().trim(); 1514 } 1515 int index = trimmedDisplayText.indexOf(","); 1516 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText) 1517 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1518 .terminateToken(trimmedDisplayText) : trimmedDisplayText; 1519 } 1520 1521 // Visible for testing. 1522 // Use this method to generate text to display in a chip. 1523 /*package*/ String createChipDisplayText(RecipientEntry entry) { 1524 String display = entry.getDisplayName(); 1525 String address = entry.getDestination(); 1526 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1527 display = null; 1528 } 1529 if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) { 1530 // Tokenize out the address in case the address already 1531 // contained the username as well. 1532 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1533 if (tokenized != null && tokenized.length > 0) { 1534 address = tokenized[0].getAddress(); 1535 } 1536 } 1537 if (!TextUtils.isEmpty(display)) { 1538 return display; 1539 } else if (!TextUtils.isEmpty(address)){ 1540 return address; 1541 } else { 1542 return new Rfc822Token(display, address, null).toString(); 1543 } 1544 } 1545 1546 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1547 String displayText = createAddressText(entry); 1548 if (TextUtils.isEmpty(displayText)) { 1549 return null; 1550 } 1551 SpannableString chipText = null; 1552 // Always leave a blank space at the end of a chip. 1553 int end = getSelectionEnd(); 1554 int start = mTokenizer.findTokenStart(getText(), end); 1555 int textLength = displayText.length()-1; 1556 chipText = new SpannableString(displayText); 1557 if (!mNoChips) { 1558 try { 1559 RecipientChip chip = constructChipSpan(entry, start, pressed, 1560 false /* leave space for contact icon */); 1561 chipText.setSpan(chip, 0, textLength, 1562 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1563 chip.setOriginalText(chipText.toString()); 1564 } catch (NullPointerException e) { 1565 Log.e(TAG, e.getMessage(), e); 1566 return null; 1567 } 1568 } 1569 return chipText; 1570 } 1571 1572 /** 1573 * When an item in the suggestions list has been clicked, create a chip from the 1574 * contact information of the selected item. 1575 */ 1576 @Override 1577 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1578 submitItemAtPosition(position); 1579 } 1580 1581 private void submitItemAtPosition(int position) { 1582 RecipientEntry entry = createValidatedEntry( 1583 (RecipientEntry)getAdapter().getItem(position)); 1584 if (entry == null) { 1585 return; 1586 } 1587 clearComposingText(); 1588 1589 int end = getSelectionEnd(); 1590 int start = mTokenizer.findTokenStart(getText(), end); 1591 1592 Editable editable = getText(); 1593 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1594 CharSequence chip = createChip(entry, false); 1595 if (chip != null && start >= 0 && end >= 0) { 1596 editable.replace(start, end, chip); 1597 } 1598 sanitizeBetween(); 1599 } 1600 1601 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1602 if (item == null) { 1603 return null; 1604 } 1605 final RecipientEntry entry; 1606 // If the display name and the address are the same, or if this is a 1607 // valid contact, but the destination is invalid, then make this a fake 1608 // recipient that is editable. 1609 String destination = item.getDestination(); 1610 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1611 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(), 1612 destination, item.isValid()); 1613 } else if (RecipientEntry.isCreatedRecipient(item.getContactId()) 1614 && (TextUtils.isEmpty(item.getDisplayName()) 1615 || TextUtils.equals(item.getDisplayName(), destination) 1616 || (mValidator != null && !mValidator.isValid(destination)))) { 1617 entry = RecipientEntry.constructFakeEntry(destination, item.isValid()); 1618 } else { 1619 entry = item; 1620 } 1621 return entry; 1622 } 1623 1624 /** Returns a collection of contact Id for each chip inside this View. */ 1625 /* package */ Collection<Long> getContactIds() { 1626 final Set<Long> result = new HashSet<Long>(); 1627 RecipientChip[] chips = getSortedRecipients(); 1628 if (chips != null) { 1629 for (RecipientChip chip : chips) { 1630 result.add(chip.getContactId()); 1631 } 1632 } 1633 return result; 1634 } 1635 1636 1637 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1638 /* package */ Collection<Long> getDataIds() { 1639 final Set<Long> result = new HashSet<Long>(); 1640 RecipientChip [] chips = getSortedRecipients(); 1641 if (chips != null) { 1642 for (RecipientChip chip : chips) { 1643 result.add(chip.getDataId()); 1644 } 1645 } 1646 return result; 1647 } 1648 1649 // Visible for testing. 1650 /* package */RecipientChip[] getSortedRecipients() { 1651 RecipientChip[] recips = getSpannable() 1652 .getSpans(0, getText().length(), RecipientChip.class); 1653 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1654 .asList(recips)); 1655 final Spannable spannable = getSpannable(); 1656 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1657 1658 @Override 1659 public int compare(RecipientChip first, RecipientChip second) { 1660 int firstStart = spannable.getSpanStart(first); 1661 int secondStart = spannable.getSpanStart(second); 1662 if (firstStart < secondStart) { 1663 return -1; 1664 } else if (firstStart > secondStart) { 1665 return 1; 1666 } else { 1667 return 0; 1668 } 1669 } 1670 }); 1671 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1672 } 1673 1674 @Override 1675 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1676 return false; 1677 } 1678 1679 @Override 1680 public void onDestroyActionMode(ActionMode mode) { 1681 } 1682 1683 @Override 1684 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1685 return false; 1686 } 1687 1688 /** 1689 * No chips are selectable. 1690 */ 1691 @Override 1692 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1693 return false; 1694 } 1695 1696 // Visible for testing. 1697 /* package */ImageSpan getMoreChip() { 1698 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1699 MoreImageSpan.class); 1700 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1701 } 1702 1703 private MoreImageSpan createMoreSpan(int count) { 1704 String moreText = String.format(mMoreItem.getText().toString(), count); 1705 TextPaint morePaint = new TextPaint(getPaint()); 1706 morePaint.setTextSize(mMoreItem.getTextSize()); 1707 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1708 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1709 + mMoreItem.getPaddingRight(); 1710 int height = getLineHeight(); 1711 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1712 Canvas canvas = new Canvas(drawable); 1713 int adjustedHeight = height; 1714 Layout layout = getLayout(); 1715 if (layout != null) { 1716 adjustedHeight -= layout.getLineDescent(0); 1717 } 1718 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1719 1720 Drawable result = new BitmapDrawable(getResources(), drawable); 1721 result.setBounds(0, 0, width, height); 1722 return new MoreImageSpan(result); 1723 } 1724 1725 // Visible for testing. 1726 /*package*/ void createMoreChipPlainText() { 1727 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one. 1728 Editable text = getText(); 1729 int start = 0; 1730 int end = start; 1731 for (int i = 0; i < CHIP_LIMIT; i++) { 1732 end = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1733 start = end; // move to the next token and get its end. 1734 } 1735 // Now, count total addresses. 1736 start = 0; 1737 int tokenCount = countTokens(text); 1738 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT); 1739 SpannableString chipText = new SpannableString(text.subSequence(end, text.length())); 1740 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1741 text.replace(end, text.length(), chipText); 1742 mMoreChip = moreSpan; 1743 } 1744 1745 // Visible for testing. 1746 /* package */int countTokens(Editable text) { 1747 int tokenCount = 0; 1748 int start = 0; 1749 while (start < text.length()) { 1750 start = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1751 tokenCount++; 1752 if (start >= text.length()) { 1753 break; 1754 } 1755 } 1756 return tokenCount; 1757 } 1758 1759 /** 1760 * Create the more chip. The more chip is text that replaces any chips that 1761 * do not fit in the pre-defined available space when the 1762 * RecipientEditTextView loses focus. 1763 */ 1764 // Visible for testing. 1765 /* package */ void createMoreChip() { 1766 if (mNoChips) { 1767 createMoreChipPlainText(); 1768 return; 1769 } 1770 1771 if (!mShouldShrink) { 1772 return; 1773 } 1774 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1775 if (tempMore.length > 0) { 1776 getSpannable().removeSpan(tempMore[0]); 1777 } 1778 RecipientChip[] recipients = getSortedRecipients(); 1779 1780 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1781 mMoreChip = null; 1782 return; 1783 } 1784 Spannable spannable = getSpannable(); 1785 int numRecipients = recipients.length; 1786 int overage = numRecipients - CHIP_LIMIT; 1787 MoreImageSpan moreSpan = createMoreSpan(overage); 1788 mRemovedSpans = new ArrayList<RecipientChip>(); 1789 int totalReplaceStart = 0; 1790 int totalReplaceEnd = 0; 1791 Editable text = getText(); 1792 for (int i = numRecipients - overage; i < recipients.length; i++) { 1793 mRemovedSpans.add(recipients[i]); 1794 if (i == numRecipients - overage) { 1795 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1796 } 1797 if (i == recipients.length - 1) { 1798 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1799 } 1800 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1801 int spanStart = spannable.getSpanStart(recipients[i]); 1802 int spanEnd = spannable.getSpanEnd(recipients[i]); 1803 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1804 } 1805 spannable.removeSpan(recipients[i]); 1806 } 1807 if (totalReplaceEnd < text.length()) { 1808 totalReplaceEnd = text.length(); 1809 } 1810 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1811 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1812 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1813 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1814 text.replace(start, end, chipText); 1815 mMoreChip = moreSpan; 1816 // If adding the +more chip goes over the limit, resize accordingly. 1817 if (!isPhoneQuery() && getLineCount() > mMaxLines) { 1818 setMaxLines(getLineCount()); 1819 } 1820 } 1821 1822 /** 1823 * Replace the more chip, if it exists, with all of the recipient chips it had 1824 * replaced when the RecipientEditTextView gains focus. 1825 */ 1826 // Visible for testing. 1827 /*package*/ void removeMoreChip() { 1828 if (mMoreChip != null) { 1829 Spannable span = getSpannable(); 1830 span.removeSpan(mMoreChip); 1831 mMoreChip = null; 1832 // Re-add the spans that were removed. 1833 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1834 // Recreate each removed span. 1835 RecipientChip[] recipients = getSortedRecipients(); 1836 // Start the search for tokens after the last currently visible 1837 // chip. 1838 if (recipients == null || recipients.length == 0) { 1839 return; 1840 } 1841 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1842 Editable editable = getText(); 1843 for (RecipientChip chip : mRemovedSpans) { 1844 int chipStart; 1845 int chipEnd; 1846 String token; 1847 // Need to find the location of the chip, again. 1848 token = (String) chip.getOriginalText(); 1849 // As we find the matching recipient for the remove spans, 1850 // reduce the size of the string we need to search. 1851 // That way, if there are duplicates, we always find the correct 1852 // recipient. 1853 chipStart = editable.toString().indexOf(token, end); 1854 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1855 // Only set the span if we found a matching token. 1856 if (chipStart != -1) { 1857 editable.setSpan(chip, chipStart, chipEnd, 1858 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1859 } 1860 } 1861 mRemovedSpans.clear(); 1862 } 1863 } 1864 } 1865 1866 /** 1867 * Show specified chip as selected. If the RecipientChip is just an email address, 1868 * selecting the chip will take the contents of the chip and place it at 1869 * the end of the RecipientEditTextView for inline editing. If the 1870 * RecipientChip is a complete contact, then selecting the chip 1871 * will change the background color of the chip, show the delete icon, 1872 * and a popup window with the address in use highlighted and any other 1873 * alternate addresses for the contact. 1874 * @param currentChip Chip to select. 1875 * @return A RecipientChip in the selected state or null if the chip 1876 * just contained an email address. 1877 */ 1878 private RecipientChip selectChip(RecipientChip currentChip) { 1879 if (shouldShowEditableText(currentChip)) { 1880 CharSequence text = currentChip.getValue(); 1881 Editable editable = getText(); 1882 getSpannable().removeSpan(currentChip); 1883 setCursorVisible(true); 1884 setSelection(editable.length()); 1885 return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text, 1886 isValid(text.toString())), -1); 1887 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1888 int start = getChipStart(currentChip); 1889 int end = getChipEnd(currentChip); 1890 getSpannable().removeSpan(currentChip); 1891 RecipientChip newChip; 1892 try { 1893 if (mNoChips) { 1894 return null; 1895 } 1896 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1897 } catch (NullPointerException e) { 1898 Log.e(TAG, e.getMessage(), e); 1899 return null; 1900 } 1901 Editable editable = getText(); 1902 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1903 if (start == -1 || end == -1) { 1904 Log.d(TAG, "The chip being selected no longer exists but should."); 1905 } else { 1906 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1907 } 1908 newChip.setSelected(true); 1909 if (shouldShowEditableText(newChip)) { 1910 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1911 } 1912 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1913 setCursorVisible(false); 1914 return newChip; 1915 } else { 1916 int start = getChipStart(currentChip); 1917 int end = getChipEnd(currentChip); 1918 getSpannable().removeSpan(currentChip); 1919 RecipientChip newChip; 1920 try { 1921 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1922 } catch (NullPointerException e) { 1923 Log.e(TAG, e.getMessage(), e); 1924 return null; 1925 } 1926 Editable editable = getText(); 1927 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1928 if (start == -1 || end == -1) { 1929 Log.d(TAG, "The chip being selected no longer exists but should."); 1930 } else { 1931 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1932 } 1933 newChip.setSelected(true); 1934 if (shouldShowEditableText(newChip)) { 1935 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1936 } 1937 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1938 setCursorVisible(false); 1939 return newChip; 1940 } 1941 } 1942 1943 private boolean shouldShowEditableText(RecipientChip currentChip) { 1944 long contactId = currentChip.getContactId(); 1945 return contactId == RecipientEntry.INVALID_CONTACT 1946 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT); 1947 } 1948 1949 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1950 int width, Context context) { 1951 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1952 int bottom = calculateOffsetFromBottom(line); 1953 // Align the alternates popup with the left side of the View, 1954 // regardless of the position of the chip tapped. 1955 popup.setWidth(width); 1956 popup.setAnchorView(this); 1957 popup.setVerticalOffset(bottom); 1958 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1959 popup.setOnItemClickListener(new OnItemClickListener() { 1960 @Override 1961 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1962 unselectChip(currentChip); 1963 popup.dismiss(); 1964 } 1965 }); 1966 popup.show(); 1967 ListView listView = popup.getListView(); 1968 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1969 listView.setItemChecked(0, true); 1970 } 1971 1972 /** 1973 * Remove selection from this chip. Unselecting a RecipientChip will render 1974 * the chip without a delete icon and with an unfocused background. This is 1975 * called when the RecipientChip no longer has focus. 1976 */ 1977 private void unselectChip(RecipientChip chip) { 1978 int start = getChipStart(chip); 1979 int end = getChipEnd(chip); 1980 Editable editable = getText(); 1981 mSelectedChip = null; 1982 if (start == -1 || end == -1) { 1983 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing"); 1984 setSelection(editable.length()); 1985 commitDefault(); 1986 } else { 1987 getSpannable().removeSpan(chip); 1988 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1989 editable.removeSpan(chip); 1990 try { 1991 if (!mNoChips) { 1992 editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false), 1993 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1994 } 1995 } catch (NullPointerException e) { 1996 Log.e(TAG, e.getMessage(), e); 1997 } 1998 } 1999 setCursorVisible(true); 2000 setSelection(editable.length()); 2001 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 2002 mAlternatesPopup.dismiss(); 2003 } 2004 } 2005 2006 /** 2007 * Return whether a touch event was inside the delete target of 2008 * a selected chip. It is in the delete target if: 2009 * 1) the x and y points of the event are within the 2010 * delete assset. 2011 * 2) the point tapped would have caused a cursor to appear 2012 * right after the selected chip. 2013 * @return boolean 2014 */ 2015 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 2016 // Figure out the bounds of this chip and whether or not 2017 // the user clicked in the X portion. 2018 return chip.isSelected() && offset == getChipEnd(chip); 2019 } 2020 2021 /** 2022 * Remove the chip and any text associated with it from the RecipientEditTextView. 2023 */ 2024 // Visible for testing. 2025 /*pacakge*/ void removeChip(RecipientChip chip) { 2026 Spannable spannable = getSpannable(); 2027 int spanStart = spannable.getSpanStart(chip); 2028 int spanEnd = spannable.getSpanEnd(chip); 2029 Editable text = getText(); 2030 int toDelete = spanEnd; 2031 boolean wasSelected = chip == mSelectedChip; 2032 // Clear that there is a selected chip before updating any text. 2033 if (wasSelected) { 2034 mSelectedChip = null; 2035 } 2036 // Always remove trailing spaces when removing a chip. 2037 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') { 2038 toDelete++; 2039 } 2040 spannable.removeSpan(chip); 2041 if (spanStart >= 0 && toDelete > 0) { 2042 text.delete(spanStart, toDelete); 2043 } 2044 if (wasSelected) { 2045 clearSelectedChip(); 2046 } 2047 } 2048 2049 /** 2050 * Replace this currently selected chip with a new chip 2051 * that uses the contact data provided. 2052 */ 2053 // Visible for testing. 2054 /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) { 2055 boolean wasSelected = chip == mSelectedChip; 2056 if (wasSelected) { 2057 mSelectedChip = null; 2058 } 2059 int start = getChipStart(chip); 2060 int end = getChipEnd(chip); 2061 getSpannable().removeSpan(chip); 2062 Editable editable = getText(); 2063 CharSequence chipText = createChip(entry, false); 2064 if (chipText != null) { 2065 if (start == -1 || end == -1) { 2066 Log.e(TAG, "The chip to replace does not exist but should."); 2067 editable.insert(0, chipText); 2068 } else { 2069 if (!TextUtils.isEmpty(chipText)) { 2070 // There may be a space to replace with this chip's new 2071 // associated space. Check for it 2072 int toReplace = end; 2073 while (toReplace >= 0 && toReplace < editable.length() 2074 && editable.charAt(toReplace) == ' ') { 2075 toReplace++; 2076 } 2077 editable.replace(start, toReplace, chipText); 2078 } 2079 } 2080 } 2081 setCursorVisible(true); 2082 if (wasSelected) { 2083 clearSelectedChip(); 2084 } 2085 } 2086 2087 /** 2088 * Handle click events for a chip. When a selected chip receives a click 2089 * event, see if that event was in the delete icon. If so, delete it. 2090 * Otherwise, unselect the chip. 2091 */ 2092 public void onClick(RecipientChip chip, int offset, float x, float y) { 2093 if (chip.isSelected()) { 2094 if (isInDelete(chip, offset, x, y)) { 2095 removeChip(chip); 2096 } else { 2097 clearSelectedChip(); 2098 } 2099 } 2100 } 2101 2102 private boolean chipsPending() { 2103 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 2104 } 2105 2106 @Override 2107 public void removeTextChangedListener(TextWatcher watcher) { 2108 mTextWatcher = null; 2109 super.removeTextChangedListener(watcher); 2110 } 2111 2112 private class RecipientTextWatcher implements TextWatcher { 2113 2114 @Override 2115 public void afterTextChanged(Editable s) { 2116 // If the text has been set to null or empty, make sure we remove 2117 // all the spans we applied. 2118 if (TextUtils.isEmpty(s)) { 2119 // Remove all the chips spans. 2120 Spannable spannable = getSpannable(); 2121 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 2122 RecipientChip.class); 2123 for (RecipientChip chip : chips) { 2124 spannable.removeSpan(chip); 2125 } 2126 if (mMoreChip != null) { 2127 spannable.removeSpan(mMoreChip); 2128 } 2129 return; 2130 } 2131 // Get whether there are any recipients pending addition to the 2132 // view. If there are, don't do anything in the text watcher. 2133 if (chipsPending()) { 2134 return; 2135 } 2136 // If the user is editing a chip, don't clear it. 2137 if (mSelectedChip != null 2138 && shouldShowEditableText(mSelectedChip)) { 2139 setCursorVisible(true); 2140 setSelection(getText().length()); 2141 clearSelectedChip(); 2142 } 2143 int length = s.length(); 2144 // Make sure there is content there to parse and that it is 2145 // not just the commit character. 2146 if (length > 1) { 2147 char last; 2148 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 2149 int len = length() - 1; 2150 if (end != len) { 2151 last = s.charAt(end); 2152 } else { 2153 last = s.charAt(len); 2154 } 2155 if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { 2156 commitByCharacter(); 2157 } else if (last == COMMIT_CHAR_SPACE) { 2158 if (!isPhoneQuery()) { 2159 // Check if this is a valid email address. If it is, 2160 // commit it. 2161 String text = getText().toString(); 2162 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2163 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 2164 tokenStart)); 2165 if (!TextUtils.isEmpty(sub) && mValidator != null && 2166 mValidator.isValid(sub)) { 2167 commitByCharacter(); 2168 } 2169 } 2170 } 2171 } 2172 } 2173 2174 @Override 2175 public void onTextChanged(CharSequence s, int start, int before, int count) { 2176 // This is a delete; check to see if the insertion point is on a space 2177 // following a chip. 2178 if (before > count) { 2179 // If the item deleted is a space, and the thing before the 2180 // space is a chip, delete the entire span. 2181 int selStart = getSelectionStart(); 2182 RecipientChip[] repl = getSpannable().getSpans(selStart, selStart, 2183 RecipientChip.class); 2184 if (repl.length > 0) { 2185 // There is a chip there! Just remove it. 2186 Editable editable = getText(); 2187 // Add the separator token. 2188 int tokenStart = mTokenizer.findTokenStart(editable, selStart); 2189 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart); 2190 tokenEnd = tokenEnd + 1; 2191 if (tokenEnd > editable.length()) { 2192 tokenEnd = editable.length(); 2193 } 2194 editable.delete(tokenStart, tokenEnd); 2195 getSpannable().removeSpan(repl[0]); 2196 } 2197 } else if (count > before) { 2198 scrollBottomIntoView(); 2199 } 2200 } 2201 2202 @Override 2203 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 2204 // Do nothing. 2205 } 2206 } 2207 2208 private void scrollBottomIntoView() { 2209 if (mScrollView != null) { 2210 mScrollView.scrollBy(0, (int) (getLineCount() * mChipHeight)); 2211 } 2212 } 2213 2214 /** 2215 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}. 2216 */ 2217 private void handlePasteClip(ClipData clip) { 2218 removeTextChangedListener(mTextWatcher); 2219 2220 if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ 2221 for (int i = 0; i < clip.getItemCount(); i++) { 2222 CharSequence paste = clip.getItemAt(i).getText(); 2223 if (paste != null) { 2224 int start = getSelectionStart(); 2225 int end = getSelectionEnd(); 2226 Editable editable = getText(); 2227 if (start >= 0 && end >= 0 && start != end) { 2228 editable.append(paste, start, end); 2229 } else { 2230 editable.insert(end, paste); 2231 } 2232 handlePasteAndReplace(); 2233 } 2234 } 2235 } 2236 2237 mHandler.post(mAddTextWatcher); 2238 } 2239 2240 @Override 2241 public boolean onTextContextMenuItem(int id) { 2242 if (id == android.R.id.paste) { 2243 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2244 Context.CLIPBOARD_SERVICE); 2245 handlePasteClip(clipboard.getPrimaryClip()); 2246 return true; 2247 } 2248 return super.onTextContextMenuItem(id); 2249 } 2250 2251 private void handlePasteAndReplace() { 2252 ArrayList<RecipientChip> created = handlePaste(); 2253 if (created != null && created.size() > 0) { 2254 // Perform reverse lookups on the pasted contacts. 2255 IndividualReplacementTask replace = new IndividualReplacementTask(); 2256 replace.execute(created); 2257 } 2258 } 2259 2260 // Visible for testing. 2261 /* package */ArrayList<RecipientChip> handlePaste() { 2262 String text = getText().toString(); 2263 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2264 String lastAddress = text.substring(originalTokenStart); 2265 int tokenStart = originalTokenStart; 2266 int prevTokenStart = tokenStart; 2267 RecipientChip findChip = null; 2268 ArrayList<RecipientChip> created = new ArrayList<RecipientChip>(); 2269 if (tokenStart != 0) { 2270 // There are things before this! 2271 while (tokenStart != 0 && findChip == null) { 2272 prevTokenStart = tokenStart; 2273 tokenStart = mTokenizer.findTokenStart(text, tokenStart); 2274 findChip = findChip(tokenStart); 2275 } 2276 if (tokenStart != originalTokenStart) { 2277 if (findChip != null) { 2278 tokenStart = prevTokenStart; 2279 } 2280 int tokenEnd; 2281 RecipientChip createdChip; 2282 while (tokenStart < originalTokenStart) { 2283 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(), 2284 tokenStart)); 2285 commitChip(tokenStart, tokenEnd, getText()); 2286 createdChip = findChip(tokenStart); 2287 if (createdChip == null) { 2288 break; 2289 } 2290 // +1 for the space at the end. 2291 tokenStart = getSpannable().getSpanEnd(createdChip) + 1; 2292 created.add(createdChip); 2293 } 2294 } 2295 } 2296 // Take a look at the last token. If the token has been completed with a 2297 // commit character, create a chip. 2298 if (isCompletedToken(lastAddress)) { 2299 Editable editable = getText(); 2300 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart); 2301 commitChip(tokenStart, editable.length(), editable); 2302 created.add(findChip(tokenStart)); 2303 } 2304 return created; 2305 } 2306 2307 // Visible for testing. 2308 /* package */int movePastTerminators(int tokenEnd) { 2309 if (tokenEnd >= length()) { 2310 return tokenEnd; 2311 } 2312 char atEnd = getText().toString().charAt(tokenEnd); 2313 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) { 2314 tokenEnd++; 2315 } 2316 // This token had not only an end token character, but also a space 2317 // separating it from the next token. 2318 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') { 2319 tokenEnd++; 2320 } 2321 return tokenEnd; 2322 } 2323 2324 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 2325 private RecipientChip createFreeChip(RecipientEntry entry) { 2326 try { 2327 if (mNoChips) { 2328 return null; 2329 } 2330 return constructChipSpan(entry, -1, false, 2331 false /*leave space for contact icon */); 2332 } catch (NullPointerException e) { 2333 Log.e(TAG, e.getMessage(), e); 2334 return null; 2335 } 2336 } 2337 2338 @Override 2339 protected Void doInBackground(Void... params) { 2340 if (mIndividualReplacements != null) { 2341 mIndividualReplacements.cancel(true); 2342 } 2343 // For each chip in the list, look up the matching contact. 2344 // If there is a match, replace that chip with the matching 2345 // chip. 2346 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 2347 RecipientChip[] existingChips = getSortedRecipients(); 2348 for (int i = 0; i < existingChips.length; i++) { 2349 originalRecipients.add(existingChips[i]); 2350 } 2351 if (mRemovedSpans != null) { 2352 originalRecipients.addAll(mRemovedSpans); 2353 } 2354 ArrayList<String> addresses = new ArrayList<String>(); 2355 RecipientChip chip; 2356 for (int i = 0; i < originalRecipients.size(); i++) { 2357 chip = originalRecipients.get(i); 2358 if (chip != null) { 2359 addresses.add(createAddressText(chip.getEntry())); 2360 } 2361 } 2362 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2363 .getMatchingRecipients(getContext(), addresses); 2364 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 2365 for (final RecipientChip temp : originalRecipients) { 2366 RecipientEntry entry = null; 2367 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2368 && getSpannable().getSpanStart(temp) != -1) { 2369 // Replace this. 2370 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 2371 .getDestination()))); 2372 } 2373 if (entry != null) { 2374 replacements.add(createFreeChip(entry)); 2375 } else { 2376 replacements.add(temp); 2377 } 2378 } 2379 if (replacements != null && replacements.size() > 0) { 2380 mHandler.post(new Runnable() { 2381 @Override 2382 public void run() { 2383 Editable oldText = getText(); 2384 int start, end; 2385 int i = 0; 2386 for (RecipientChip chip : originalRecipients) { 2387 // Find the location of the chip in the text currently shown. 2388 start = oldText.getSpanStart(chip); 2389 if (start != -1) { 2390 end = oldText.getSpanEnd(chip); 2391 oldText.removeSpan(chip); 2392 RecipientChip replacement = replacements.get(i); 2393 // Make sure we always have just 1 space at the 2394 // end to separate this chip from the next chip. 2395 SpannableString displayText = new SpannableString( 2396 createAddressText(replacement.getEntry()).trim() + " "); 2397 displayText.setSpan(replacement, 0, displayText.length()-1, 2398 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2399 // Replace the old text we found with with the new display text, 2400 // which now may also contain the display name of the recipient. 2401 oldText.replace(start, end, displayText); 2402 replacement.setOriginalText(displayText.toString()); 2403 } 2404 i++; 2405 } 2406 originalRecipients.clear(); 2407 } 2408 }); 2409 } 2410 return null; 2411 } 2412 } 2413 2414 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 2415 @SuppressWarnings("unchecked") 2416 @Override 2417 protected Void doInBackground(Object... params) { 2418 // For each chip in the list, look up the matching contact. 2419 // If there is a match, replace that chip with the matching 2420 // chip. 2421 final ArrayList<RecipientChip> originalRecipients = 2422 (ArrayList<RecipientChip>) params[0]; 2423 ArrayList<String> addresses = new ArrayList<String>(); 2424 RecipientChip chip; 2425 for (int i = 0; i < originalRecipients.size(); i++) { 2426 chip = originalRecipients.get(i); 2427 if (chip != null) { 2428 addresses.add(createAddressText(chip.getEntry())); 2429 } 2430 } 2431 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2432 .getMatchingRecipients(getContext(), addresses); 2433 for (final RecipientChip temp : originalRecipients) { 2434 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2435 && getSpannable().getSpanStart(temp) != -1) { 2436 // Replace this. 2437 RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress( 2438 temp.getEntry().getDestination()).toLowerCase())); 2439 // If we don't have a validated contact match, just use the 2440 // entry as it existed before. 2441 if (entry == null && !isPhoneQuery()) { 2442 entry = temp.getEntry(); 2443 } 2444 final RecipientEntry tempEntry = entry; 2445 if (tempEntry != null) { 2446 mHandler.post(new Runnable() { 2447 @Override 2448 public void run() { 2449 replaceChip(temp, tempEntry); 2450 } 2451 }); 2452 } 2453 } 2454 } 2455 return null; 2456 } 2457 } 2458 2459 2460 /** 2461 * MoreImageSpan is a simple class created for tracking the existence of a 2462 * more chip across activity restarts/ 2463 */ 2464 private class MoreImageSpan extends ImageSpan { 2465 public MoreImageSpan(Drawable b) { 2466 super(b); 2467 } 2468 } 2469 2470 @Override 2471 public boolean onDown(MotionEvent e) { 2472 return false; 2473 } 2474 2475 @Override 2476 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2477 // Do nothing. 2478 return false; 2479 } 2480 2481 @Override 2482 public void onLongPress(MotionEvent event) { 2483 if (mSelectedChip != null) { 2484 return; 2485 } 2486 float x = event.getX(); 2487 float y = event.getY(); 2488 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2489 RecipientChip currentChip = findChip(offset); 2490 if (currentChip != null) { 2491 if (mDragEnabled) { 2492 // Start drag-and-drop for the selected chip. 2493 startDrag(currentChip); 2494 } else { 2495 // Copy the selected chip email address. 2496 showCopyDialog(currentChip.getEntry().getDestination()); 2497 } 2498 } 2499 } 2500 2501 /** 2502 * Enables drag-and-drop for chips. 2503 */ 2504 public void enableDrag() { 2505 mDragEnabled = true; 2506 } 2507 2508 /** 2509 * Starts drag-and-drop for the selected chip. 2510 */ 2511 private void startDrag(RecipientChip currentChip) { 2512 String address = currentChip.getEntry().getDestination(); 2513 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA); 2514 2515 // Start drag mode. 2516 startDrag(data, new RecipientChipShadow(currentChip), null, 0); 2517 2518 // Remove the current chip, so drag-and-drop will result in a move. 2519 // TODO (phamm): consider readd this chip if it's dropped outside a target. 2520 removeChip(currentChip); 2521 } 2522 2523 /** 2524 * Handles drag event. 2525 */ 2526 @Override 2527 public boolean onDragEvent(DragEvent event) { 2528 switch (event.getAction()) { 2529 case DragEvent.ACTION_DRAG_STARTED: 2530 // Only handle plain text drag and drop. 2531 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); 2532 case DragEvent.ACTION_DRAG_ENTERED: 2533 requestFocus(); 2534 return true; 2535 case DragEvent.ACTION_DROP: 2536 handlePasteClip(event.getClipData()); 2537 return true; 2538 } 2539 return false; 2540 } 2541 2542 /** 2543 * Drag shadow for a {@link RecipientChip}. 2544 */ 2545 private final class RecipientChipShadow extends DragShadowBuilder { 2546 private final RecipientChip mChip; 2547 2548 public RecipientChipShadow(RecipientChip chip) { 2549 mChip = chip; 2550 } 2551 2552 @Override 2553 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 2554 Rect rect = mChip.getDrawable().getBounds(); 2555 shadowSize.set(rect.width(), rect.height()); 2556 shadowTouchPoint.set(rect.centerX(), rect.centerY()); 2557 } 2558 2559 @Override 2560 public void onDrawShadow(Canvas canvas) { 2561 mChip.getDrawable().draw(canvas); 2562 } 2563 } 2564 2565 private void showCopyDialog(final String address) { 2566 mCopyAddress = address; 2567 mCopyDialog.setTitle(address); 2568 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout); 2569 mCopyDialog.setCancelable(true); 2570 mCopyDialog.setCanceledOnTouchOutside(true); 2571 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1); 2572 button.setOnClickListener(this); 2573 int btnTitleId; 2574 if (isPhoneQuery()) { 2575 btnTitleId = R.string.copy_number; 2576 } else { 2577 btnTitleId = R.string.copy_email; 2578 } 2579 String buttonTitle = getContext().getResources().getString(btnTitleId); 2580 button.setText(buttonTitle); 2581 mCopyDialog.setOnDismissListener(this); 2582 mCopyDialog.show(); 2583 } 2584 2585 @Override 2586 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2587 // Do nothing. 2588 return false; 2589 } 2590 2591 @Override 2592 public void onShowPress(MotionEvent e) { 2593 // Do nothing. 2594 } 2595 2596 @Override 2597 public boolean onSingleTapUp(MotionEvent e) { 2598 // Do nothing. 2599 return false; 2600 } 2601 2602 @Override 2603 public void onDismiss(DialogInterface dialog) { 2604 mCopyAddress = null; 2605 } 2606 2607 @Override 2608 public void onClick(View v) { 2609 // Copy this to the clipboard. 2610 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2611 Context.CLIPBOARD_SERVICE); 2612 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2613 mCopyDialog.dismiss(); 2614 } 2615 2616 protected boolean isPhoneQuery() { 2617 return getAdapter() != null 2618 && ((BaseRecipientAdapter) getAdapter()).getQueryType() 2619 == BaseRecipientAdapter.QUERY_TYPE_PHONE; 2620 } 2621} 2622