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