RecipientEditTextView.java revision ae7e41106f289f2668c54fff6c457c6fc91ab4a9
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.ClipboardManager; 22import android.content.Context; 23import android.content.DialogInterface; 24import android.content.DialogInterface.OnDismissListener; 25import android.graphics.Bitmap; 26import android.graphics.BitmapFactory; 27import android.graphics.Canvas; 28import android.graphics.Matrix; 29import android.graphics.Rect; 30import android.graphics.RectF; 31import android.graphics.drawable.BitmapDrawable; 32import android.graphics.drawable.Drawable; 33import android.os.AsyncTask; 34import android.os.Handler; 35import android.os.Message; 36import android.os.Parcelable; 37import android.text.Editable; 38import android.text.InputType; 39import android.text.Layout; 40import android.text.Spannable; 41import android.text.SpannableString; 42import android.text.SpannableStringBuilder; 43import android.text.Spanned; 44import android.text.TextPaint; 45import android.text.TextUtils; 46import android.text.TextWatcher; 47import android.text.method.QwertyKeyListener; 48import android.text.style.ImageSpan; 49import android.text.util.Rfc822Token; 50import android.text.util.Rfc822Tokenizer; 51import android.util.AttributeSet; 52import android.util.Log; 53import android.view.ActionMode; 54import android.view.ActionMode.Callback; 55import android.view.GestureDetector; 56import android.view.KeyEvent; 57import android.view.LayoutInflater; 58import android.view.Menu; 59import android.view.MenuItem; 60import android.view.MotionEvent; 61import android.view.View; 62import android.view.View.OnClickListener; 63import android.view.ViewParent; 64import android.widget.AdapterView; 65import android.widget.AdapterView.OnItemClickListener; 66import android.widget.Filterable; 67import android.widget.ListAdapter; 68import android.widget.ListPopupWindow; 69import android.widget.ListView; 70import android.widget.MultiAutoCompleteTextView; 71import android.widget.PopupWindow; 72import android.widget.ScrollView; 73import android.widget.TextView; 74 75import java.util.ArrayList; 76import java.util.Arrays; 77import java.util.Collection; 78import java.util.Collections; 79import java.util.Comparator; 80import java.util.HashMap; 81import java.util.HashSet; 82import java.util.Set; 83 84/** 85 * RecipientEditTextView is an auto complete text view for use with applications 86 * that use the new Chips UI for addressing a message to recipients. 87 */ 88public class RecipientEditTextView extends MultiAutoCompleteTextView implements 89 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, 90 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener, 91 PopupWindow.OnDismissListener { 92 93 private static final String TAG = "RecipientEditTextView"; 94 95 // TODO: get correct number/ algorithm from with UX. 96 private static final int CHIP_LIMIT = 2; 97 98 private Drawable mChipBackground = null; 99 100 private Drawable mChipDelete = null; 101 102 private int mChipPadding; 103 104 private Tokenizer mTokenizer; 105 106 private Drawable mChipBackgroundPressed; 107 108 private RecipientChip mSelectedChip; 109 110 private int mAlternatesLayout; 111 112 private Bitmap mDefaultContactPhoto; 113 114 private ImageSpan mMoreChip; 115 116 private TextView mMoreItem; 117 118 private final ArrayList<String> mPendingChips = new ArrayList<String>(); 119 120 private float mChipHeight; 121 122 private float mChipFontSize; 123 124 private Validator mValidator; 125 126 private Drawable mInvalidChipBackground; 127 128 private Handler mHandler; 129 130 private static int DISMISS = "dismiss".hashCode(); 131 132 private static final long DISMISS_DELAY = 300; 133 134 private int mPendingChipsCount = 0; 135 136 private static int sSelectedTextColor = -1; 137 138 private static final char COMMIT_CHAR_COMMA = ','; 139 140 private static final char COMMIT_CHAR_SEMICOLON = ';'; 141 142 private static final char COMMIT_CHAR_SPACE = ' '; 143 144 private ListPopupWindow mAlternatesPopup; 145 146 private ListPopupWindow mAddressPopup; 147 148 private ArrayList<RecipientChip> mTemporaryRecipients; 149 150 private ArrayList<RecipientChip> mRemovedSpans; 151 152 private boolean mShouldShrink = true; 153 154 // Chip copy fields. 155 private GestureDetector mGestureDetector; 156 157 private Dialog mCopyDialog; 158 159 private int mCopyViewRes; 160 161 private String mCopyAddress; 162 163 /** 164 * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a 165 * selected chip. 166 */ 167 private OnItemClickListener mAlternatesListener; 168 169 private int mCheckedItem; 170 private TextWatcher mTextWatcher; 171 172 private ScrollView mScrollView; 173 174 private boolean mTried; 175 176 private final Runnable mAddTextWatcher = new Runnable() { 177 @Override 178 public void run() { 179 if (mTextWatcher == null) { 180 mTextWatcher = new RecipientTextWatcher(); 181 addTextChangedListener(mTextWatcher); 182 } 183 } 184 }; 185 186 private IndividualReplacementTask mIndividualReplacements; 187 188 private Runnable mHandlePendingChips = new Runnable() { 189 190 @Override 191 public void run() { 192 handlePendingChips(); 193 } 194 195 }; 196 197 private Runnable mDelayedShrink = new Runnable() { 198 199 @Override 200 public void run() { 201 shrink(); 202 } 203 204 }; 205 206 public RecipientEditTextView(Context context, AttributeSet attrs) { 207 super(context, attrs); 208 if (sSelectedTextColor == -1) { 209 sSelectedTextColor = context.getResources().getColor(android.R.color.white); 210 } 211 mAlternatesPopup = new ListPopupWindow(context); 212 mAlternatesPopup.setOnDismissListener(this); 213 mAddressPopup = new ListPopupWindow(context); 214 mAddressPopup.setOnDismissListener(this); 215 mCopyDialog = new Dialog(context); 216 mAlternatesListener = new OnItemClickListener() { 217 @Override 218 public void onItemClick(AdapterView<?> adapterView,View view, int position, 219 long rowId) { 220 mAlternatesPopup.setOnItemClickListener(null); 221 setEnabled(true); 222 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) 223 .getRecipientEntry(position)); 224 Message delayed = Message.obtain(mHandler, DISMISS); 225 delayed.obj = mAlternatesPopup; 226 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); 227 clearComposingText(); 228 } 229 }; 230 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 231 setOnItemClickListener(this); 232 setCustomSelectionActionModeCallback(this); 233 mHandler = new Handler() { 234 @Override 235 public void handleMessage(Message msg) { 236 if (msg.what == DISMISS) { 237 ((ListPopupWindow) msg.obj).dismiss(); 238 return; 239 } 240 super.handleMessage(msg); 241 } 242 }; 243 mTextWatcher = new RecipientTextWatcher(); 244 addTextChangedListener(mTextWatcher); 245 mGestureDetector = new GestureDetector(context, this); 246 } 247 248 @Override 249 public <T extends ListAdapter & Filterable> void setAdapter(T adapter) { 250 super.setAdapter(adapter); 251 if (adapter == null) { 252 return; 253 } 254 } 255 256 @Override 257 public void onSelectionChanged(int start, int end) { 258 // When selection changes, see if it is inside the chips area. 259 // If so, move the cursor back after the chips again. 260 Spannable span = getSpannable(); 261 int textLength = getText().length(); 262 RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class); 263 if (chips != null && chips.length > 0) { 264 if (chips != null && chips.length > 0) { 265 // Grab the last chip and set the cursor to after it. 266 setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength)); 267 } 268 } 269 super.onSelectionChanged(start, end); 270 } 271 272 @Override 273 public void onRestoreInstanceState(Parcelable state) { 274 if (!TextUtils.isEmpty(getText())) { 275 super.onRestoreInstanceState(null); 276 } else { 277 super.onRestoreInstanceState(state); 278 } 279 } 280 281 /** 282 * Convenience method: Append the specified text slice to the TextView's 283 * display buffer, upgrading it to BufferType.EDITABLE if it was 284 * not already editable. Commas are excluded as they are added automatically 285 * by the view. 286 */ 287 @Override 288 public void append(CharSequence text, int start, int end) { 289 // We don't care about watching text changes while appending. 290 if (mTextWatcher != null) { 291 removeTextChangedListener(mTextWatcher); 292 } 293 super.append(text, start, end); 294 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) { 295 final String displayString = (String) text; 296 int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA); 297 if (seperatorPos != 0 && !TextUtils.isEmpty(displayString) 298 && TextUtils.getTrimmedLength(displayString) > 0) { 299 mPendingChipsCount++; 300 mPendingChips.add((String)text); 301 } 302 } 303 // Put a message on the queue to make sure we ALWAYS handle pending chips. 304 if (mPendingChipsCount > 0) { 305 postHandlePendingChips(); 306 } 307 mHandler.post(mAddTextWatcher); 308 } 309 310 @Override 311 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { 312 super.onFocusChanged(hasFocus, direction, previous); 313 if (!hasFocus) { 314 shrink(); 315 } else { 316 expand(); 317 scrollLineIntoView(getLineCount()); 318 } 319 } 320 321 @Override 322 public void performValidation() { 323 // Do nothing. Chips handles its own validation. 324 } 325 326 private void shrink() { 327 if (mSelectedChip != null 328 && mSelectedChip.getEntry().getContactId() != RecipientEntry.INVALID_CONTACT) { 329 clearSelectedChip(); 330 } else { 331 if (getWidth() <= 0) { 332 // We don't have the width yet which means the view hasn't been drawn yet 333 // and there is no reason to attempt to commit chips yet. 334 // This focus lost must be the result of an orientation change 335 // or an initial rendering. 336 // Re-post the shrink for later. 337 mHandler.removeCallbacks(mDelayedShrink); 338 mHandler.post(mDelayedShrink); 339 return; 340 } 341 // Reset any pending chips as they would have been handled 342 // when the field lost focus. 343 if (mPendingChipsCount > 0) { 344 postHandlePendingChips(); 345 } else { 346 Editable editable = getText(); 347 int end = getSelectionEnd(); 348 int start = mTokenizer.findTokenStart(editable, end); 349 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 350 if ((chips == null || chips.length == 0)) { 351 Editable text = getText(); 352 int whatEnd = mTokenizer.findTokenEnd(text, start); 353 // This token was already tokenized, so skip past the ending token. 354 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') { 355 whatEnd++; 356 } 357 // In the middle of chip; treat this as an edit 358 // and commit the whole token. 359 int selEnd = getSelectionEnd(); 360 if (whatEnd != selEnd && whatEnd != editable.toString().trim().length()) { 361 handleEdit(start, whatEnd); 362 } else { 363 commitChip(start, end, editable); 364 } 365 } 366 } 367 mHandler.post(mAddTextWatcher); 368 } 369 createMoreChip(); 370 } 371 372 private void expand() { 373 removeMoreChip(); 374 setCursorVisible(true); 375 Editable text = getText(); 376 setSelection(text != null && text.length() > 0 ? text.length() : 0); 377 // If there are any temporary chips, try replacing them now that the user 378 // has expanded the field. 379 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) { 380 new RecipientReplacementTask().execute(); 381 mTemporaryRecipients = null; 382 } 383 } 384 385 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) { 386 paint.setTextSize(mChipFontSize); 387 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) { 388 Log.d(TAG, "Max width is negative: " + maxWidth); 389 } 390 return TextUtils.ellipsize(text, paint, maxWidth, 391 TextUtils.TruncateAt.END); 392 } 393 394 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 395 // Ellipsize the text so that it takes AT MOST the entire width of the 396 // autocomplete text entry area. Make sure to leave space for padding 397 // on the sides. 398 int height = (int) mChipHeight; 399 int deleteWidth = height; 400 CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint, 401 calculateAvailableWidth(true) - deleteWidth); 402 403 // Make sure there is a minimum chip width so the user can ALWAYS 404 // tap a chip without difficulty. 405 int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 406 ellipsizedText.length())) 407 + (mChipPadding * 2) + deleteWidth); 408 409 // Create the background of the chip. 410 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 411 Canvas canvas = new Canvas(tmpBitmap); 412 if (mChipBackgroundPressed != null) { 413 mChipBackgroundPressed.setBounds(0, 0, width, height); 414 mChipBackgroundPressed.draw(canvas); 415 paint.setColor(sSelectedTextColor); 416 // Vertically center the text in the chip. 417 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 418 getTextYOffset((String) ellipsizedText, paint, height), paint); 419 // Make the delete a square. 420 Rect backgroundPadding = new Rect(); 421 mChipBackgroundPressed.getPadding(backgroundPadding); 422 mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left, 423 0 + backgroundPadding.top, 424 width - backgroundPadding.right, 425 height - backgroundPadding.bottom); 426 mChipDelete.draw(canvas); 427 } else { 428 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 429 } 430 return tmpBitmap; 431 } 432 433 /** 434 * Get the background drawable for a RecipientChip. 435 */ 436 public Drawable getChipBackground(RecipientEntry contact) { 437 String destination = contact.getDestination(); 438 return (mValidator != null && !TextUtils.isEmpty(destination) && mValidator 439 .isValid(destination)) ? mChipBackground : mInvalidChipBackground; 440 } 441 442 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 443 // Ellipsize the text so that it takes AT MOST the entire width of the 444 // autocomplete text entry area. Make sure to leave space for padding 445 // on the sides. 446 int height = (int) mChipHeight; 447 int iconWidth = height; 448 String displayText = 449 !TextUtils.isEmpty(contact.getDisplayName()) ? contact.getDisplayName() : 450 !TextUtils.isEmpty(contact.getDestination()) ? contact.getDestination() : ""; 451 CharSequence ellipsizedText = ellipsizeText(displayText, paint, 452 calculateAvailableWidth(false) - iconWidth); 453 // Make sure there is a minimum chip width so the user can ALWAYS 454 // tap a chip without difficulty. 455 int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 456 ellipsizedText.length())) 457 + (mChipPadding * 2) + iconWidth); 458 459 // Create the background of the chip. 460 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 461 Canvas canvas = new Canvas(tmpBitmap); 462 Drawable background = getChipBackground(contact); 463 if (background != null) { 464 background.setBounds(0, 0, width, height); 465 background.draw(canvas); 466 467 // Don't draw photos for recipients that have been typed in. 468 if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) { 469 byte[] photoBytes = contact.getPhotoBytes(); 470 // There may not be a photo yet if anything but the first contact address 471 // was selected. 472 if (photoBytes == null && contact.getPhotoThumbnailUri() != null) { 473 // TODO: cache this in the recipient entry? 474 ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact 475 .getPhotoThumbnailUri()); 476 photoBytes = contact.getPhotoBytes(); 477 } 478 479 Bitmap photo; 480 if (photoBytes != null) { 481 photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); 482 } else { 483 // TODO: can the scaled down default photo be cached? 484 photo = mDefaultContactPhoto; 485 } 486 // Draw the photo on the left side. 487 if (photo != null) { 488 RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight()); 489 Rect backgroundPadding = new Rect(); 490 mChipBackground.getPadding(backgroundPadding); 491 RectF dst = new RectF(width - iconWidth + backgroundPadding.left, 492 0 + backgroundPadding.top, 493 width - backgroundPadding.right, 494 height - backgroundPadding.bottom); 495 Matrix matrix = new Matrix(); 496 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL); 497 canvas.drawBitmap(photo, matrix, paint); 498 } 499 } else { 500 // Don't leave any space for the icon. It isn't being drawn. 501 iconWidth = 0; 502 } 503 paint.setColor(getContext().getResources().getColor(android.R.color.black)); 504 // Vertically center the text in the chip. 505 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 506 getTextYOffset((String)ellipsizedText, paint, height), paint); 507 } else { 508 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 509 } 510 return tmpBitmap; 511 } 512 513 private float getTextYOffset(String text, TextPaint paint, int height) { 514 Rect bounds = new Rect(); 515 paint.getTextBounds((String)text, 0, text.length(), bounds); 516 int textHeight = bounds.bottom - bounds.top - (int)paint.descent(); 517 return height - ((height - textHeight) / 2); 518 } 519 520 public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed) 521 throws NullPointerException { 522 if (mChipBackground == null) { 523 throw new NullPointerException( 524 "Unable to render any chips as setChipDimensions was not called."); 525 } 526 Layout layout = getLayout(); 527 528 TextPaint paint = getPaint(); 529 float defaultSize = paint.getTextSize(); 530 int defaultColor = paint.getColor(); 531 532 Bitmap tmpBitmap; 533 if (pressed) { 534 tmpBitmap = createSelectedChip(contact, paint, layout); 535 536 } else { 537 tmpBitmap = createUnselectedChip(contact, paint, layout); 538 } 539 540 // Pass the full text, un-ellipsized, to the chip. 541 Drawable result = new BitmapDrawable(getResources(), tmpBitmap); 542 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight()); 543 RecipientChip recipientChip = new RecipientChip(result, contact, offset); 544 // Return text to the original size. 545 paint.setTextSize(defaultSize); 546 paint.setColor(defaultColor); 547 return recipientChip; 548 } 549 550 /** 551 * Calculate the bottom of the line the chip will be located on using: 552 * 1) which line the chip appears on 553 * 2) the height of a chip 554 * 3) padding built into the edit text view 555 */ 556 private int calculateOffsetFromBottom(int line) { 557 // Line offsets start at zero. 558 int actualLine = getLineCount() - (line + 1); 559 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop()) 560 + getDropDownVerticalOffset(); 561 } 562 563 /** 564 * Get the max amount of space a chip can take up. The formula takes into 565 * account the width of the EditTextView, any view padding, and padding 566 * that will be added to the chip. 567 */ 568 private float calculateAvailableWidth(boolean pressed) { 569 return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2); 570 } 571 572 /** 573 * Set all chip dimensions and resources. This has to be done from the 574 * application as this is a static library. 575 * @param chipBackground 576 * @param chipBackgroundPressed 577 * @param invalidChip 578 * @param chipDelete 579 * @param defaultContact 580 * @param moreResource 581 * @param alternatesLayout 582 * @param chipHeight 583 * @param padding Padding around the text in a chip 584 * @param chipFontSize 585 * @param copyViewRes 586 */ 587 public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed, 588 Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource, 589 int alternatesLayout, float chipHeight, float padding, 590 float chipFontSize, int copyViewRes) { 591 mChipBackground = chipBackground; 592 mChipBackgroundPressed = chipBackgroundPressed; 593 mChipDelete = chipDelete; 594 mChipPadding = (int) padding; 595 mAlternatesLayout = alternatesLayout; 596 mDefaultContactPhoto = defaultContact; 597 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(moreResource, null); 598 mChipHeight = chipHeight; 599 mChipFontSize = chipFontSize; 600 mInvalidChipBackground = invalidChip; 601 mCopyViewRes = copyViewRes; 602 } 603 604 // Visible for testing. 605 /* package */ void setMoreItem(TextView moreItem) { 606 mMoreItem = moreItem; 607 } 608 609 610 // Visible for testing. 611 /* package */ void setChipBackground(Drawable chipBackground) { 612 mChipBackground = chipBackground; 613 } 614 615 // Visible for testing. 616 /* package */ void setChipHeight(int height) { 617 mChipHeight = height; 618 } 619 620 /** 621 * Set whether to shrink the recipients field such that at most 622 * one line of recipients chips are shown when the field loses 623 * focus. By default, the number of displayed recipients will be 624 * limited and a "more" chip will be shown when focus is lost. 625 * @param shrink 626 */ 627 public void setOnFocusListShrinkRecipients(boolean shrink) { 628 mShouldShrink = shrink; 629 } 630 631 @Override 632 public void onSizeChanged(int width, int height, int oldw, int oldh) { 633 super.onSizeChanged(width, height, oldw, oldh); 634 if (width != 0 && height != 0) { 635 if (mPendingChipsCount > 0) { 636 postHandlePendingChips(); 637 } else { 638 checkChipWidths(); 639 } 640 } 641 // Try to find the scroll view parent, if it exists. 642 if (mScrollView == null && !mTried) { 643 ViewParent parent = getParent(); 644 while (parent != null && !(parent instanceof ScrollView)) { 645 parent = parent.getParent(); 646 } 647 if (parent != null) { 648 mScrollView = (ScrollView) parent; 649 } 650 mTried = true; 651 } 652 } 653 654 private void postHandlePendingChips() { 655 mHandler.removeCallbacks(mHandlePendingChips); 656 mHandler.post(mHandlePendingChips); 657 } 658 659 private void checkChipWidths() { 660 // Check the widths of the associated chips. 661 RecipientChip[] chips = getSortedRecipients(); 662 if (chips != null) { 663 Rect bounds; 664 for (RecipientChip chip : chips) { 665 bounds = chip.getDrawable().getBounds(); 666 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) { 667 // Need to redraw that chip. 668 replaceChip(chip, chip.getEntry()); 669 } 670 } 671 } 672 } 673 674 private void handlePendingChips() { 675 if (getWidth() <= 0) { 676 // The widget has not been sized yet. 677 // This will be called as a result of onSizeChanged 678 // at a later point. 679 return; 680 } 681 682 if (mPendingChipsCount <= 0) { 683 return; 684 } 685 686 synchronized (mPendingChips) { 687 Editable editable = getText(); 688 // Tokenize! 689 for (int i = 0; i < mPendingChips.size(); i++) { 690 String current = mPendingChips.get(i); 691 int tokenStart = editable.toString().indexOf(current); 692 int tokenEnd = tokenStart + current.length(); 693 if (tokenStart >= 0) { 694 // When we have a valid token, include it with the token 695 // to the left. 696 if (tokenEnd < editable.length() - 2 697 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { 698 tokenEnd++; 699 } 700 createReplacementChip(tokenStart, tokenEnd, editable); 701 } 702 mPendingChipsCount--; 703 } 704 sanitizeSpannable(); 705 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0 706 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { 707 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { 708 new RecipientReplacementTask().execute(); 709 mTemporaryRecipients = null; 710 } else { 711 // Create the "more" chip 712 mIndividualReplacements = new IndividualReplacementTask(); 713 mIndividualReplacements.execute(new ArrayList<RecipientChip>( 714 mTemporaryRecipients.subList(0, CHIP_LIMIT))); 715 716 createMoreChip(); 717 } 718 } else { 719 // There are too many recipients to look up, so just fall back 720 // to showing addresses for all of them. 721 mTemporaryRecipients = null; 722 createMoreChip(); 723 } 724 mPendingChipsCount = 0; 725 mPendingChips.clear(); 726 } 727 } 728 729 /** 730 * Remove any characters after the last valid chip. 731 */ 732 private void sanitizeSpannable() { 733 // Find the last chip; eliminate any commit characters after it. 734 RecipientChip[] chips = getRecipients(); 735 if (chips != null && chips.length > 0) { 736 int end; 737 ImageSpan lastSpan; 738 mMoreChip = getMoreChip(); 739 if (mMoreChip != null) { 740 lastSpan = mMoreChip; 741 } else { 742 lastSpan = chips[chips.length - 1]; 743 } 744 end = getSpannable().getSpanEnd(lastSpan); 745 Editable editable = getText(); 746 int length = editable.length(); 747 if (length > end) { 748 // See what characters occur after that and eliminate them. 749 if (Log.isLoggable(TAG, Log.DEBUG)) { 750 Log.d(TAG, "There were extra characters after the last tokenizable entry." 751 + editable); 752 } 753 editable.delete(end + 1, length); 754 } 755 } 756 } 757 758 /** 759 * Create a chip that represents just the email address of a recipient. At some later 760 * point, this chip will be attached to a real contact entry, if one exists. 761 */ 762 private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { 763 if (alreadyHasChip(tokenStart, tokenEnd)) { 764 // There is already a chip present at this location. 765 // Don't recreate it. 766 return; 767 } 768 String token = editable.toString().substring(tokenStart, tokenEnd); 769 int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); 770 if (commitCharIndex == token.length() - 1) { 771 token = token.substring(0, token.length() - 1); 772 } 773 RecipientEntry entry = createTokenizedEntry(token); 774 if (entry != null) { 775 String destText = createDisplayText(entry); 776 // Always leave a blank space at the end of a chip. 777 int textLength = destText.length(); 778 SpannableString chipText = new SpannableString(destText); 779 int end = getSelectionEnd(); 780 int start = mTokenizer.findTokenStart(getText(), end); 781 RecipientChip chip = null; 782 try { 783 chip = constructChipSpan(entry, start, false); 784 chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 785 } catch (NullPointerException e) { 786 Log.e(TAG, e.getMessage(), e); 787 } 788 editable.replace(tokenStart, tokenEnd, chipText); 789 // Add this chip to the list of entries "to replace" 790 if (chip != null) { 791 if (mTemporaryRecipients == null) { 792 mTemporaryRecipients = new ArrayList<RecipientChip>(); 793 } 794 chip.setOriginalText(chipText.toString()); 795 mTemporaryRecipients.add(chip); 796 } 797 } 798 } 799 800 private RecipientEntry createTokenizedEntry(String token) { 801 if (TextUtils.isEmpty(token)) { 802 return null; 803 } 804 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 805 String display = null; 806 if (isValid(token) && tokens != null && tokens.length > 0) { 807 // If we can get a name from tokenizing, then generate an entry from 808 // this. 809 display = tokens[0].getName(); 810 if (!TextUtils.isEmpty(display)) { 811 return RecipientEntry.constructGeneratedEntry(display, token); 812 } else { 813 display = tokens[0].getAddress(); 814 if (!TextUtils.isEmpty(display)) { 815 return RecipientEntry.constructFakeEntry(display); 816 } 817 } 818 } 819 // Unable to validate the token or to create a valid token from it. 820 // Just create a chip the user can edit. 821 String validatedToken = null; 822 if (mValidator != null && !mValidator.isValid(token)) { 823 // Try fixing up the entry using the validator. 824 validatedToken = mValidator.fixText(token).toString(); 825 if (!TextUtils.isEmpty(validatedToken)) { 826 if (validatedToken.contains(token)) { 827 // protect against the case of a validator with a null domain, 828 // which doesn't add a domain to the token 829 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 830 if (tokenized.length > 0) { 831 validatedToken = tokenized[0].getAddress(); 832 } 833 } else { 834 // We ran into a case where the token was invalid and removed 835 // by the validator. In this case, just use the original token 836 // and let the user sort out the error chip. 837 validatedToken = null; 838 } 839 } 840 } 841 // Otherwise, fallback to just creating an editable email address chip. 842 return RecipientEntry 843 .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token); 844 } 845 846 private boolean isValid(String text) { 847 return mValidator == null ? true : mValidator.isValid(text); 848 } 849 850 private String tokenizeAddress(String destination) { 851 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); 852 if (tokens != null && tokens.length > 0) { 853 return tokens[0].getAddress(); 854 } 855 return destination; 856 } 857 858 @Override 859 public void setTokenizer(Tokenizer tokenizer) { 860 mTokenizer = tokenizer; 861 super.setTokenizer(mTokenizer); 862 } 863 864 @Override 865 public void setValidator(Validator validator) { 866 mValidator = validator; 867 super.setValidator(validator); 868 } 869 870 /** 871 * We cannot use the default mechanism for replaceText. Instead, 872 * we override onItemClickListener so we can get all the associated 873 * contact information including display text, address, and id. 874 */ 875 @Override 876 protected void replaceText(CharSequence text) { 877 return; 878 } 879 880 /** 881 * Dismiss any selected chips when the back key is pressed. 882 */ 883 @Override 884 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 885 if (keyCode == KeyEvent.KEYCODE_BACK) { 886 clearSelectedChip(); 887 } 888 return super.onKeyPreIme(keyCode, event); 889 } 890 891 /** 892 * Monitor key presses in this view to see if the user types 893 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. 894 * If the user has entered text that has contact matches and types 895 * a commit key, create a chip from the topmost matching contact. 896 * If the user has entered text that has no contact matches and types 897 * a commit key, then create a chip from the text they have entered. 898 */ 899 @Override 900 public boolean onKeyUp(int keyCode, KeyEvent event) { 901 switch (keyCode) { 902 case KeyEvent.KEYCODE_ENTER: 903 case KeyEvent.KEYCODE_DPAD_CENTER: 904 if (event.hasNoModifiers()) { 905 if (commitDefault()) { 906 return true; 907 } 908 if (mSelectedChip != null) { 909 clearSelectedChip(); 910 return true; 911 } else if (focusNext()) { 912 return true; 913 } 914 } 915 break; 916 case KeyEvent.KEYCODE_TAB: 917 if (event.hasNoModifiers()) { 918 if (mSelectedChip != null) { 919 clearSelectedChip(); 920 } else { 921 commitDefault(); 922 } 923 if (focusNext()) { 924 return true; 925 } 926 } 927 } 928 return super.onKeyUp(keyCode, event); 929 } 930 931 private boolean focusNext() { 932 View next = focusSearch(View.FOCUS_DOWN); 933 if (next != null) { 934 next.requestFocus(); 935 return true; 936 } 937 return false; 938 } 939 940 /** 941 * Create a chip from the default selection. If the popup is showing, the 942 * default is the first item in the popup suggestions list. Otherwise, it is 943 * whatever the user had typed in. End represents where the the tokenizer 944 * should search for a token to turn into a chip. 945 * @return If a chip was created from a real contact. 946 */ 947 private boolean commitDefault() { 948 Editable editable = getText(); 949 int end = getSelectionEnd(); 950 int start = mTokenizer.findTokenStart(editable, end); 951 952 if (shouldCreateChip(start, end)) { 953 int whatEnd = mTokenizer.findTokenEnd(getText(), start); 954 // In the middle of chip; treat this as an edit 955 // and commit the whole token. 956 if (whatEnd != getSelectionEnd()) { 957 handleEdit(start, whatEnd); 958 return true; 959 } 960 return commitChip(start, end , editable); 961 } 962 return false; 963 } 964 965 private void commitByCharacter() { 966 Editable editable = getText(); 967 int end = getSelectionEnd(); 968 int start = mTokenizer.findTokenStart(editable, end); 969 if (shouldCreateChip(start, end)) { 970 commitChip(start, end, editable); 971 } 972 setSelection(getText().length()); 973 } 974 975 private boolean commitChip(int start, int end, Editable editable) { 976 if (getAdapter().getCount() > 0 && enoughToFilter()) { 977 // choose the first entry. 978 submitItemAtPosition(0); 979 dismissDropDown(); 980 return true; 981 } else { 982 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 983 if (editable.length() > tokenEnd && editable.charAt(tokenEnd) == ',') { 984 tokenEnd++; 985 } 986 String text = editable.toString().substring(start, tokenEnd); 987 clearComposingText(); 988 if (text != null && text.length() > 0 && !text.equals(" ")) { 989 RecipientEntry entry = createTokenizedEntry(text); 990 if (entry != null) { 991 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 992 CharSequence chipText = createChip(entry, false); 993 if (chipText != null) { 994 editable.replace(start, end, chipText); 995 } 996 } 997 dismissDropDown(); 998 sanitizeBetween(); 999 return true; 1000 } 1001 } 1002 return false; 1003 } 1004 1005 // Visible for testing. 1006 /* package */ void sanitizeBetween() { 1007 // Find the last chip. 1008 RecipientChip[] recips = getSortedRecipients(); 1009 if (recips != null && recips.length > 0) { 1010 RecipientChip last = recips[recips.length - 1]; 1011 RecipientChip beforeLast = null; 1012 if (recips.length > 1) { 1013 beforeLast = recips[recips.length - 2]; 1014 } 1015 int startLooking = 0; 1016 int end = getSpannable().getSpanStart(last); 1017 if (beforeLast != null) { 1018 startLooking = getSpannable().getSpanEnd(beforeLast); 1019 Editable text = getText(); 1020 if (startLooking == -1 || startLooking > text.length() - 1) { 1021 // There is nothing after this chip. 1022 return; 1023 } 1024 if (text.charAt(startLooking) == ' ') { 1025 startLooking++; 1026 } 1027 } 1028 if (startLooking >= 0 && end >= 0 && startLooking != end) { 1029 getText().delete(startLooking, end); 1030 } 1031 } 1032 } 1033 1034 private boolean shouldCreateChip(int start, int end) { 1035 return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1036 } 1037 1038 private boolean alreadyHasChip(int start, int end) { 1039 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 1040 if ((chips == null || chips.length == 0)) { 1041 return false; 1042 } 1043 return true; 1044 } 1045 1046 private void handleEdit(int start, int end) { 1047 if (start == -1 || end == -1) { 1048 // This chip no longer exists in the field. 1049 dismissDropDown(); 1050 return; 1051 } 1052 // This is in the middle of a chip, so select out the whole chip 1053 // and commit it. 1054 Editable editable = getText(); 1055 setSelection(end); 1056 String text = getText().toString().substring(start, end); 1057 if (!TextUtils.isEmpty(text)) { 1058 RecipientEntry entry = RecipientEntry.constructFakeEntry(text); 1059 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1060 CharSequence chipText = createChip(entry, false); 1061 editable.replace(start, getSelectionEnd(), chipText); 1062 } 1063 dismissDropDown(); 1064 } 1065 1066 /** 1067 * If there is a selected chip, delegate the key events 1068 * to the selected chip. 1069 */ 1070 @Override 1071 public boolean onKeyDown(int keyCode, KeyEvent event) { 1072 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { 1073 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1074 mAlternatesPopup.dismiss(); 1075 } 1076 removeChip(mSelectedChip); 1077 } 1078 1079 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1080 return true; 1081 } 1082 1083 return super.onKeyDown(keyCode, event); 1084 } 1085 1086 // Visible for testing. 1087 /* package */ Spannable getSpannable() { 1088 return getText(); 1089 } 1090 1091 private int getChipStart(RecipientChip chip) { 1092 return getSpannable().getSpanStart(chip); 1093 } 1094 1095 private int getChipEnd(RecipientChip chip) { 1096 return getSpannable().getSpanEnd(chip); 1097 } 1098 1099 /** 1100 * Instead of filtering on the entire contents of the edit box, 1101 * this subclass method filters on the range from 1102 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1103 * if the length of that range meets or exceeds {@link #getThreshold} 1104 * and makes sure that the range is not already a Chip. 1105 */ 1106 @Override 1107 protected void performFiltering(CharSequence text, int keyCode) { 1108 if (enoughToFilter()) { 1109 int end = getSelectionEnd(); 1110 int start = mTokenizer.findTokenStart(text, end); 1111 // If this is a RecipientChip, don't filter 1112 // on its contents. 1113 Spannable span = getSpannable(); 1114 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1115 if (chips != null && chips.length > 0) { 1116 return; 1117 } 1118 } 1119 super.performFiltering(text, keyCode); 1120 } 1121 1122 private void clearSelectedChip() { 1123 if (mSelectedChip != null) { 1124 unselectChip(mSelectedChip); 1125 mSelectedChip = null; 1126 } 1127 setCursorVisible(true); 1128 } 1129 1130 /** 1131 * Monitor touch events in the RecipientEditTextView. 1132 * If the view does not have focus, any tap on the view 1133 * will just focus the view. If the view has focus, determine 1134 * if the touch target is a recipient chip. If it is and the chip 1135 * is not selected, select it and clear any other selected chips. 1136 * If it isn't, then select that chip. 1137 */ 1138 @Override 1139 public boolean onTouchEvent(MotionEvent event) { 1140 if (!isFocused()) { 1141 // Ignore any chip taps until this view is focused. 1142 return super.onTouchEvent(event); 1143 } 1144 boolean handled = super.onTouchEvent(event); 1145 int action = event.getAction(); 1146 boolean chipWasSelected = false; 1147 if (mSelectedChip == null) { 1148 mGestureDetector.onTouchEvent(event); 1149 } 1150 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1151 float x = event.getX(); 1152 float y = event.getY(); 1153 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1154 RecipientChip currentChip = findChip(offset); 1155 if (currentChip != null) { 1156 if (action == MotionEvent.ACTION_UP) { 1157 if (mSelectedChip != null && mSelectedChip != currentChip) { 1158 clearSelectedChip(); 1159 mSelectedChip = selectChip(currentChip); 1160 } else if (mSelectedChip == null) { 1161 setSelection(getText().length()); 1162 commitDefault(); 1163 mSelectedChip = selectChip(currentChip); 1164 } else { 1165 onClick(mSelectedChip, offset, x, y); 1166 } 1167 } 1168 chipWasSelected = true; 1169 handled = true; 1170 } else if (mSelectedChip != null 1171 && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) { 1172 chipWasSelected = true; 1173 } 1174 } 1175 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1176 clearSelectedChip(); 1177 } 1178 return handled; 1179 } 1180 1181 private void scrollLineIntoView(int line) { 1182 if (mScrollView != null) { 1183 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1184 } 1185 } 1186 1187 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1188 int width, Context context) { 1189 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1190 int bottom = calculateOffsetFromBottom(line); 1191 // Align the alternates popup with the left side of the View, 1192 // regardless of the position of the chip tapped. 1193 alternatesPopup.setWidth(width); 1194 setEnabled(false); 1195 alternatesPopup.setAnchorView(this); 1196 alternatesPopup.setVerticalOffset(bottom); 1197 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1198 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1199 // Clear the checked item. 1200 mCheckedItem = -1; 1201 alternatesPopup.show(); 1202 ListView listView = alternatesPopup.getListView(); 1203 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1204 // Checked item would be -1 if the adapter has not 1205 // loaded the view that should be checked yet. The 1206 // variable will be set correctly when onCheckedItemChanged 1207 // is called in a separate thread. 1208 if (mCheckedItem != -1) { 1209 listView.setItemChecked(mCheckedItem, true); 1210 mCheckedItem = -1; 1211 } 1212 } 1213 1214 // Dismiss listener for alterns and single address popup. 1215 @Override 1216 public void onDismiss() { 1217 setEnabled(true); 1218 } 1219 1220 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1221 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1222 mAlternatesLayout, this); 1223 } 1224 1225 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1226 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1227 .getEntry()); 1228 } 1229 1230 @Override 1231 public void onCheckedItemChanged(int position) { 1232 ListView listView = mAlternatesPopup.getListView(); 1233 if (listView != null && listView.getCheckedItemCount() == 0) { 1234 listView.setItemChecked(position, true); 1235 } 1236 mCheckedItem = position; 1237 } 1238 1239 // TODO: This algorithm will need a lot of tweaking after more people have used 1240 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1241 // what comes before the finger. 1242 private int putOffsetInRange(int o) { 1243 int offset = o; 1244 Editable text = getText(); 1245 int length = text.length(); 1246 // Remove whitespace from end to find "real end" 1247 int realLength = length; 1248 for (int i = length - 1; i >= 0; i--) { 1249 if (text.charAt(i) == ' ') { 1250 realLength--; 1251 } else { 1252 break; 1253 } 1254 } 1255 1256 // If the offset is beyond or at the end of the text, 1257 // leave it alone. 1258 if (offset >= realLength) { 1259 return offset; 1260 } 1261 Editable editable = getText(); 1262 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1263 // Keep walking backward! 1264 offset--; 1265 } 1266 return offset; 1267 } 1268 1269 private int findText(Editable text, int offset) { 1270 if (text.charAt(offset) != ' ') { 1271 return offset; 1272 } 1273 return -1; 1274 } 1275 1276 private RecipientChip findChip(int offset) { 1277 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1278 // Find the chip that contains this offset. 1279 for (int i = 0; i < chips.length; i++) { 1280 RecipientChip chip = chips[i]; 1281 int start = getChipStart(chip); 1282 int end = getChipEnd(chip); 1283 if (offset >= start && offset <= end) { 1284 return chip; 1285 } 1286 } 1287 return null; 1288 } 1289 1290 // Visible for testing. 1291 /* package */ String createDisplayText(RecipientEntry entry) { 1292 String display = entry.getDisplayName(); 1293 String address = entry.getDestination(); 1294 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1295 display = null; 1296 } 1297 if (address != null) { 1298 // Tokenize out the address in case the address already 1299 // contained the username as well. 1300 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1301 if (tokenized != null && tokenized.length > 0) { 1302 address = tokenized[0].getAddress(); 1303 } 1304 } 1305 Rfc822Token token = new Rfc822Token(display, address, null); 1306 String displayText = token.toString(); 1307 String trimmedDisplayText = displayText.trim(); 1308 int index = trimmedDisplayText.indexOf(","); 1309 return index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1310 .terminateToken(displayText) : displayText; 1311 } 1312 1313 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1314 String displayText = createDisplayText(entry); 1315 // Always leave a blank space at the end of a chip. 1316 int textLength = displayText.length(); 1317 SpannableString chipText = new SpannableString(displayText); 1318 int end = getSelectionEnd(); 1319 int start = mTokenizer.findTokenStart(getText(), end); 1320 try { 1321 RecipientChip chip = constructChipSpan(entry, start, pressed); 1322 chipText.setSpan(chip, 0, textLength, 1323 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1324 chip.setOriginalText(chipText.toString()); 1325 } catch (NullPointerException e) { 1326 Log.e(TAG, e.getMessage(), e); 1327 return null; 1328 } 1329 1330 return chipText; 1331 } 1332 1333 /** 1334 * When an item in the suggestions list has been clicked, create a chip from the 1335 * contact information of the selected item. 1336 */ 1337 @Override 1338 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1339 submitItemAtPosition(position); 1340 } 1341 1342 private void submitItemAtPosition(int position) { 1343 RecipientEntry entry = createValidatedEntry( 1344 (RecipientEntry)getAdapter().getItem(position)); 1345 if (entry == null) { 1346 return; 1347 } 1348 clearComposingText(); 1349 1350 int end = getSelectionEnd(); 1351 int start = mTokenizer.findTokenStart(getText(), end); 1352 1353 Editable editable = getText(); 1354 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1355 CharSequence chip = createChip(entry, false); 1356 if (chip != null) { 1357 editable.replace(start, end, chip); 1358 } 1359 sanitizeBetween(); 1360 } 1361 1362 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1363 if (item == null) { 1364 return null; 1365 } 1366 final RecipientEntry entry; 1367 // If the display name and the address are the same, or if this is a 1368 // valid contact, but the destination is invalid, then make this a fake 1369 // recipient that is editable. 1370 String destination = item.getDestination(); 1371 if (TextUtils.isEmpty(item.getDisplayName()) 1372 || TextUtils.equals(item.getDisplayName(), destination) 1373 || (mValidator != null && !mValidator.isValid(destination))) { 1374 entry = RecipientEntry.constructFakeEntry(destination); 1375 } else { 1376 entry = item; 1377 } 1378 return entry; 1379 } 1380 1381 /** Returns a collection of contact Id for each chip inside this View. */ 1382 /* package */ Collection<Long> getContactIds() { 1383 final Set<Long> result = new HashSet<Long>(); 1384 RecipientChip[] chips = getRecipients(); 1385 if (chips != null) { 1386 for (RecipientChip chip : chips) { 1387 result.add(chip.getContactId()); 1388 } 1389 } 1390 return result; 1391 } 1392 1393 private RecipientChip[] getRecipients() { 1394 return getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1395 } 1396 1397 // Visible for testing. 1398 /* package */ RecipientChip[] getSortedRecipients() { 1399 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1400 .asList(getRecipients())); 1401 final Spannable spannable = getSpannable(); 1402 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1403 1404 @Override 1405 public int compare(RecipientChip first, RecipientChip second) { 1406 int firstStart = spannable.getSpanStart(first); 1407 int secondStart = spannable.getSpanStart(second); 1408 if (firstStart < secondStart) { 1409 return -1; 1410 } else if (firstStart > secondStart) { 1411 return 1; 1412 } else { 1413 return 0; 1414 } 1415 } 1416 }); 1417 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1418 } 1419 1420 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1421 /* package */ Collection<Long> getDataIds() { 1422 final Set<Long> result = new HashSet<Long>(); 1423 RecipientChip [] chips = getRecipients(); 1424 if (chips != null) { 1425 for (RecipientChip chip : chips) { 1426 result.add(chip.getDataId()); 1427 } 1428 } 1429 return result; 1430 } 1431 1432 1433 @Override 1434 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1435 return false; 1436 } 1437 1438 @Override 1439 public void onDestroyActionMode(ActionMode mode) { 1440 } 1441 1442 @Override 1443 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1444 return false; 1445 } 1446 1447 /** 1448 * No chips are selectable. 1449 */ 1450 @Override 1451 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1452 return false; 1453 } 1454 1455 // Visible for testing. 1456 /* package */ImageSpan getMoreChip() { 1457 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1458 MoreImageSpan.class); 1459 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1460 } 1461 1462 /** 1463 * Create the more chip. The more chip is text that replaces any chips that 1464 * do not fit in the pre-defined available space when the 1465 * RecipientEditTextView loses focus. 1466 */ 1467 // Visible for testing. 1468 /* package */ void createMoreChip() { 1469 if (!mShouldShrink) { 1470 return; 1471 } 1472 1473 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1474 if (tempMore.length > 0) { 1475 getSpannable().removeSpan(tempMore[0]); 1476 } 1477 RecipientChip[] recipients = getSortedRecipients(); 1478 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1479 mMoreChip = null; 1480 return; 1481 } 1482 Spannable spannable = getSpannable(); 1483 int numRecipients = recipients.length; 1484 int overage = numRecipients - CHIP_LIMIT; 1485 String moreText = String.format(mMoreItem.getText().toString(), overage); 1486 TextPaint morePaint = new TextPaint(getPaint()); 1487 morePaint.setTextSize(mMoreItem.getTextSize()); 1488 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1489 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1490 + mMoreItem.getPaddingRight(); 1491 int height = getLineHeight(); 1492 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1493 Canvas canvas = new Canvas(drawable); 1494 int adjustedHeight = height; 1495 Layout layout = getLayout(); 1496 if (layout != null) { 1497 adjustedHeight -= layout.getLineDescent(0); 1498 } 1499 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1500 1501 Drawable result = new BitmapDrawable(getResources(), drawable); 1502 result.setBounds(0, 0, width, height); 1503 MoreImageSpan moreSpan = new MoreImageSpan(result); 1504 // Remove the overage chips. 1505 if (recipients == null || recipients.length == 0) { 1506 Log.w(TAG, 1507 "We have recipients. Tt should not be possible to have zero RecipientChips."); 1508 mMoreChip = null; 1509 return; 1510 } 1511 mRemovedSpans = new ArrayList<RecipientChip>(); 1512 int totalReplaceStart = 0; 1513 int totalReplaceEnd = 0; 1514 Editable text = getText(); 1515 for (int i = numRecipients - overage; i < recipients.length; i++) { 1516 mRemovedSpans.add(recipients[i]); 1517 if (i == numRecipients - overage) { 1518 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1519 } 1520 if (i == recipients.length - 1) { 1521 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1522 } 1523 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1524 int spanStart = spannable.getSpanStart(recipients[i]); 1525 int spanEnd = spannable.getSpanEnd(recipients[i]); 1526 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1527 } 1528 spannable.removeSpan(recipients[i]); 1529 } 1530 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1531 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1532 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1533 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1534 text.replace(start, end, chipText); 1535 mMoreChip = moreSpan; 1536 } 1537 1538 /** 1539 * Replace the more chip, if it exists, with all of the recipient chips it had 1540 * replaced when the RecipientEditTextView gains focus. 1541 */ 1542 // Visible for testing. 1543 /*package*/ void removeMoreChip() { 1544 if (mMoreChip != null) { 1545 Spannable span = getSpannable(); 1546 span.removeSpan(mMoreChip); 1547 mMoreChip = null; 1548 // Re-add the spans that were removed. 1549 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1550 // Recreate each removed span. 1551 RecipientChip[] recipients = getSortedRecipients(); 1552 // Start the search for tokens after the last currently visible 1553 // chip. 1554 if (recipients == null || recipients.length == 0) { 1555 return; 1556 } 1557 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1558 Editable editable = getText(); 1559 for (RecipientChip chip : mRemovedSpans) { 1560 int chipStart; 1561 int chipEnd; 1562 String token; 1563 // Need to find the location of the chip, again. 1564 token = (String) chip.getOriginalText(); 1565 // As we find the matching recipient for the remove spans, 1566 // reduce the size of the string we need to search. 1567 // That way, if there are duplicates, we always find the correct 1568 // recipient. 1569 chipStart = editable.toString().indexOf(token, end); 1570 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1571 // Only set the span if we found a matching token. 1572 if (chipStart != -1) { 1573 editable.setSpan(chip, chipStart, chipEnd, 1574 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1575 } 1576 } 1577 mRemovedSpans.clear(); 1578 } 1579 } 1580 } 1581 1582 /** 1583 * Show specified chip as selected. If the RecipientChip is just an email address, 1584 * selecting the chip will take the contents of the chip and place it at 1585 * the end of the RecipientEditTextView for inline editing. If the 1586 * RecipientChip is a complete contact, then selecting the chip 1587 * will change the background color of the chip, show the delete icon, 1588 * and a popup window with the address in use highlighted and any other 1589 * alternate addresses for the contact. 1590 * @param currentChip Chip to select. 1591 * @return A RecipientChip in the selected state or null if the chip 1592 * just contained an email address. 1593 */ 1594 public RecipientChip selectChip(RecipientChip currentChip) { 1595 if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) { 1596 CharSequence text = currentChip.getValue(); 1597 Editable editable = getText(); 1598 removeChip(currentChip); 1599 editable.append(text); 1600 setCursorVisible(true); 1601 setSelection(editable.length()); 1602 return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1); 1603 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1604 int start = getChipStart(currentChip); 1605 int end = getChipEnd(currentChip); 1606 getSpannable().removeSpan(currentChip); 1607 RecipientChip newChip; 1608 try { 1609 newChip = constructChipSpan(currentChip.getEntry(), start, true); 1610 } catch (NullPointerException e) { 1611 Log.e(TAG, e.getMessage(), e); 1612 return null; 1613 } 1614 Editable editable = getText(); 1615 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1616 if (start == -1 || end == -1) { 1617 Log.d(TAG, "The chip being selected no longer exists but should."); 1618 } else { 1619 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1620 } 1621 newChip.setSelected(true); 1622 if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) { 1623 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1624 } 1625 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1626 setCursorVisible(false); 1627 return newChip; 1628 } else { 1629 int start = getChipStart(currentChip); 1630 int end = getChipEnd(currentChip); 1631 getSpannable().removeSpan(currentChip); 1632 RecipientChip newChip; 1633 try { 1634 newChip = constructChipSpan(currentChip.getEntry(), start, true); 1635 } catch (NullPointerException e) { 1636 Log.e(TAG, e.getMessage(), e); 1637 return null; 1638 } 1639 Editable editable = getText(); 1640 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1641 if (start == -1 || end == -1) { 1642 Log.d(TAG, "The chip being selected no longer exists but should."); 1643 } else { 1644 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1645 } 1646 newChip.setSelected(true); 1647 if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) { 1648 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1649 } 1650 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1651 setCursorVisible(false); 1652 return newChip; 1653 } 1654 } 1655 1656 1657 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1658 int width, Context context) { 1659 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1660 int bottom = calculateOffsetFromBottom(line); 1661 // Align the alternates popup with the left side of the View, 1662 // regardless of the position of the chip tapped. 1663 setEnabled(false); 1664 popup.setWidth(width); 1665 popup.setAnchorView(this); 1666 popup.setVerticalOffset(bottom); 1667 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1668 popup.setOnItemClickListener(new OnItemClickListener() { 1669 @Override 1670 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1671 unselectChip(currentChip); 1672 popup.dismiss(); 1673 } 1674 }); 1675 popup.show(); 1676 ListView listView = popup.getListView(); 1677 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1678 listView.setItemChecked(0, true); 1679 } 1680 1681 /** 1682 * Remove selection from this chip. Unselecting a RecipientChip will render 1683 * the chip without a delete icon and with an unfocused background. This 1684 * is called when the RecipientChip no longer has focus. 1685 */ 1686 public void unselectChip(RecipientChip chip) { 1687 int start = getChipStart(chip); 1688 int end = getChipEnd(chip); 1689 Editable editable = getText(); 1690 mSelectedChip = null; 1691 if (start == -1 || end == -1) { 1692 Log.w(TAG, 1693 "The chip doesn't exist or may be a chip a user was editing"); 1694 setSelection(editable.length()); 1695 commitDefault(); 1696 } else { 1697 getSpannable().removeSpan(chip); 1698 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1699 editable.removeSpan(chip); 1700 try { 1701 editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end, 1702 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1703 } catch (NullPointerException e) { 1704 Log.e(TAG, e.getMessage(), e); 1705 } 1706 } 1707 setCursorVisible(true); 1708 setSelection(editable.length()); 1709 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1710 mAlternatesPopup.dismiss(); 1711 } 1712 } 1713 1714 /** 1715 * Return whether this chip contains the position passed in. 1716 */ 1717 public boolean matchesChip(RecipientChip chip, int offset) { 1718 int start = getChipStart(chip); 1719 int end = getChipEnd(chip); 1720 1721 if (start == -1 || end == -1) { 1722 return false; 1723 } 1724 return (offset >= start && offset <= end); 1725 } 1726 1727 1728 /** 1729 * Return whether a touch event was inside the delete target of 1730 * a selected chip. It is in the delete target if: 1731 * 1) the x and y points of the event are within the 1732 * delete assset. 1733 * 2) the point tapped would have caused a cursor to appear 1734 * right after the selected chip. 1735 * @return boolean 1736 */ 1737 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 1738 // Figure out the bounds of this chip and whether or not 1739 // the user clicked in the X portion. 1740 return chip.isSelected() && offset == getChipEnd(chip); 1741 } 1742 1743 /** 1744 * Remove the chip and any text associated with it from the RecipientEditTextView. 1745 */ 1746 // Visible for testing. 1747 /*pacakge*/ void removeChip(RecipientChip chip) { 1748 Spannable spannable = getSpannable(); 1749 int spanStart = spannable.getSpanStart(chip); 1750 int spanEnd = spannable.getSpanEnd(chip); 1751 Editable text = getText(); 1752 boolean wasSelected = chip == mSelectedChip; 1753 // Clear that there is a selected chip before updating any text. 1754 if (wasSelected) { 1755 mSelectedChip = null; 1756 } 1757 spannable.removeSpan(chip); 1758 text.delete(spanStart, spanEnd); 1759 if (wasSelected) { 1760 clearSelectedChip(); 1761 } 1762 } 1763 1764 /** 1765 * Replace this currently selected chip with a new chip 1766 * that uses the contact data provided. 1767 */ 1768 public void replaceChip(RecipientChip chip, RecipientEntry entry) { 1769 boolean wasSelected = chip == mSelectedChip; 1770 if (wasSelected) { 1771 mSelectedChip = null; 1772 } 1773 int start = getChipStart(chip); 1774 int end = getChipEnd(chip); 1775 getSpannable().removeSpan(chip); 1776 Editable editable = getText(); 1777 CharSequence chipText = createChip(entry, false); 1778 if (start == -1 || end == -1) { 1779 Log.e(TAG, "The chip to replace does not exist but should."); 1780 editable.insert(0, chipText); 1781 } else { 1782 if (!TextUtils.isEmpty(chipText)) { 1783 editable.replace(start, end, chipText); 1784 } 1785 } 1786 setCursorVisible(true); 1787 if (wasSelected) { 1788 clearSelectedChip(); 1789 } 1790 } 1791 1792 /** 1793 * Handle click events for a chip. When a selected chip receives a click 1794 * event, see if that event was in the delete icon. If so, delete it. 1795 * Otherwise, unselect the chip. 1796 */ 1797 public void onClick(RecipientChip chip, int offset, float x, float y) { 1798 if (chip.isSelected()) { 1799 if (isInDelete(chip, offset, x, y)) { 1800 removeChip(chip); 1801 } else { 1802 clearSelectedChip(); 1803 } 1804 } 1805 } 1806 1807 private boolean chipsPending() { 1808 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 1809 } 1810 1811 @Override 1812 public void removeTextChangedListener(TextWatcher watcher) { 1813 mTextWatcher = null; 1814 super.removeTextChangedListener(watcher); 1815 } 1816 1817 private class RecipientTextWatcher implements TextWatcher { 1818 @Override 1819 public void afterTextChanged(Editable s) { 1820 // If the text has been set to null or empty, make sure we remove 1821 // all the spans we applied. 1822 if (TextUtils.isEmpty(s)) { 1823 // Remove all the chips spans. 1824 Spannable spannable = getSpannable(); 1825 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 1826 RecipientChip.class); 1827 for (RecipientChip chip : chips) { 1828 spannable.removeSpan(chip); 1829 } 1830 if (mMoreChip != null) { 1831 spannable.removeSpan(mMoreChip); 1832 } 1833 return; 1834 } 1835 // Get whether there are any recipients pending addition to the 1836 // view. If there are, don't do anything in the text watcher. 1837 if (chipsPending()) { 1838 return; 1839 } 1840 // If the user is editing a chip, don't clear it. 1841 if (mSelectedChip != null 1842 && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) { 1843 setCursorVisible(true); 1844 setSelection(getText().length()); 1845 clearSelectedChip(); 1846 } 1847 int length = s.length(); 1848 // Make sure there is content there to parse and that it is 1849 // not just the commit character. 1850 if (length > 1) { 1851 char last; 1852 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 1853 int len = length() - 1; 1854 if (end != len) { 1855 last = s.charAt(end); 1856 } else { 1857 last = s.charAt(len); 1858 } 1859 if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { 1860 commitByCharacter(); 1861 } else if (last == COMMIT_CHAR_SPACE) { 1862 // Check if this is a valid email address. If it is, 1863 // commit it. 1864 String text = getText().toString(); 1865 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 1866 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 1867 tokenStart)); 1868 if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) { 1869 commitByCharacter(); 1870 } 1871 } 1872 } 1873 } 1874 1875 @Override 1876 public void onTextChanged(CharSequence s, int start, int before, int count) { 1877 // Do nothing. 1878 } 1879 1880 @Override 1881 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 1882 // Do nothing. 1883 } 1884 } 1885 1886 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 1887 private RecipientChip createFreeChip(RecipientEntry entry) { 1888 try { 1889 return constructChipSpan(entry, -1, false); 1890 } catch (NullPointerException e) { 1891 Log.e(TAG, e.getMessage(), e); 1892 return null; 1893 } 1894 } 1895 1896 @Override 1897 protected Void doInBackground(Void... params) { 1898 if (mIndividualReplacements != null) { 1899 mIndividualReplacements.cancel(true); 1900 } 1901 // For each chip in the list, look up the matching contact. 1902 // If there is a match, replace that chip with the matching 1903 // chip. 1904 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 1905 RecipientChip[] existingChips = getSortedRecipients(); 1906 for (int i = 0; i < existingChips.length; i++) { 1907 originalRecipients.add(existingChips[i]); 1908 } 1909 if (mRemovedSpans != null) { 1910 originalRecipients.addAll(mRemovedSpans); 1911 } 1912 String[] addresses = new String[originalRecipients.size()]; 1913 for (int i = 0; i < originalRecipients.size(); i++) { 1914 addresses[i] = createDisplayText(originalRecipients.get(i).getEntry()); 1915 } 1916 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 1917 .getMatchingRecipients(getContext(), addresses); 1918 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 1919 for (final RecipientChip temp : originalRecipients) { 1920 RecipientEntry entry = null; 1921 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 1922 && getSpannable().getSpanStart(temp) != -1) { 1923 // Replace this. 1924 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 1925 .getDestination()))); 1926 } 1927 if (entry != null) { 1928 replacements.add(createFreeChip(entry)); 1929 } else { 1930 replacements.add(temp); 1931 } 1932 } 1933 if (replacements != null && replacements.size() > 0) { 1934 mHandler.post(new Runnable() { 1935 @Override 1936 public void run() { 1937 SpannableStringBuilder text = new SpannableStringBuilder(getText() 1938 .toString()); 1939 Editable oldText = getText(); 1940 int start, end; 1941 int i = 0; 1942 for (RecipientChip chip : originalRecipients) { 1943 start = oldText.getSpanStart(chip); 1944 if (start != -1) { 1945 end = oldText.getSpanEnd(chip); 1946 text.removeSpan(chip); 1947 // Leave a spot for the space! 1948 RecipientChip replacement = replacements.get(i); 1949 text.setSpan(replacement, start, end, 1950 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1951 replacement.setOriginalText(text.toString().substring(start, end)); 1952 } 1953 i++; 1954 } 1955 Editable editable = getText(); 1956 editable.clear(); 1957 editable.insert(0, text); 1958 originalRecipients.clear(); 1959 } 1960 }); 1961 } 1962 return null; 1963 } 1964 } 1965 1966 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 1967 @SuppressWarnings("unchecked") 1968 @Override 1969 protected Void doInBackground(Object... params) { 1970 // For each chip in the list, look up the matching contact. 1971 // If there is a match, replace that chip with the matching 1972 // chip. 1973 final ArrayList<RecipientChip> originalRecipients = 1974 (ArrayList<RecipientChip>) params[0]; 1975 String[] addresses = new String[originalRecipients.size()]; 1976 for (int i = 0; i < originalRecipients.size(); i++) { 1977 addresses[i] = createDisplayText(originalRecipients.get(i).getEntry()); 1978 } 1979 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 1980 .getMatchingRecipients(getContext(), addresses); 1981 for (final RecipientChip temp : originalRecipients) { 1982 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 1983 && getSpannable().getSpanStart(temp) != -1) { 1984 // Replace this. 1985 final RecipientEntry entry = createValidatedEntry(entries 1986 .get(tokenizeAddress(temp.getEntry().getDestination()))); 1987 if (entry != null) { 1988 mHandler.post(new Runnable() { 1989 @Override 1990 public void run() { 1991 replaceChip(temp, entry); 1992 } 1993 }); 1994 } 1995 } 1996 } 1997 return null; 1998 } 1999 } 2000 2001 2002 /** 2003 * MoreImageSpan is a simple class created for tracking the existence of a 2004 * more chip across activity restarts/ 2005 */ 2006 private class MoreImageSpan extends ImageSpan { 2007 public MoreImageSpan(Drawable b) { 2008 super(b); 2009 } 2010 } 2011 2012 @Override 2013 public boolean onDown(MotionEvent e) { 2014 return false; 2015 } 2016 2017 @Override 2018 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2019 // Do nothing. 2020 return false; 2021 } 2022 2023 @Override 2024 public void onLongPress(MotionEvent event) { 2025 if (mSelectedChip != null) { 2026 return; 2027 } 2028 float x = event.getX(); 2029 float y = event.getY(); 2030 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2031 RecipientChip currentChip = findChip(offset); 2032 if (currentChip != null) { 2033 // Copy the selected chip email address. 2034 showCopyDialog(currentChip.getEntry().getDestination()); 2035 } 2036 } 2037 2038 private void showCopyDialog(final String address) { 2039 mCopyAddress = address; 2040 mCopyDialog.setTitle(address); 2041 mCopyDialog.setContentView(mCopyViewRes); 2042 mCopyDialog.setCancelable(true); 2043 mCopyDialog.setCanceledOnTouchOutside(true); 2044 mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this); 2045 mCopyDialog.setOnDismissListener(this); 2046 mCopyDialog.show(); 2047 } 2048 2049 @Override 2050 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2051 // Do nothing. 2052 return false; 2053 } 2054 2055 @Override 2056 public void onShowPress(MotionEvent e) { 2057 // Do nothing. 2058 } 2059 2060 @Override 2061 public boolean onSingleTapUp(MotionEvent e) { 2062 // Do nothing. 2063 return false; 2064 } 2065 2066 @Override 2067 public void onDismiss(DialogInterface dialog) { 2068 mCopyAddress = null; 2069 } 2070 2071 @Override 2072 public void onClick(View v) { 2073 // Copy this to the clipboard. 2074 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2075 Context.CLIPBOARD_SERVICE); 2076 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2077 mCopyDialog.dismiss(); 2078 } 2079} 2080