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