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