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