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