RecipientEditTextView.java revision 8eb031e6de46e477412d92ab0c5ef20b431f1804
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    // Visible for testing.
938    /* package */ void sanitizeBetween() {
939        // Find the last chip.
940        RecipientChip[] recips = getSortedRecipients();
941        if (recips != null && recips.length > 0) {
942            RecipientChip last = recips[recips.length - 1];
943            RecipientChip beforeLast = null;
944            if (recips.length > 1) {
945                beforeLast = recips[recips.length - 2];
946            }
947            int startLooking = 0;
948            int end = getSpannable().getSpanStart(last);
949            if (beforeLast != null) {
950                startLooking = getSpannable().getSpanEnd(beforeLast);
951                Editable text = getText();
952                if (startLooking == -1 || startLooking > text.length() - 1) {
953                    // There is nothing after this chip.
954                    return;
955                }
956                if (text.charAt(startLooking) == ' ') {
957                    startLooking++;
958                }
959            }
960            if (startLooking >= 0 && end >= 0 && startLooking != end) {
961                getText().delete(startLooking, end);
962            }
963        }
964    }
965
966    private boolean shouldCreateChip(int start, int end) {
967        return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
968    }
969
970    private boolean alreadyHasChip(int start, int end) {
971        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
972        if ((chips == null || chips.length == 0)) {
973            return false;
974        }
975        return true;
976    }
977
978    private void handleEdit(int start, int end) {
979        if (start == -1 || end == -1) {
980            // This chip no longer exists in the field.
981            dismissDropDown();
982            return;
983        }
984        // This is in the middle of a chip, so select out the whole chip
985        // and commit it.
986        Editable editable = getText();
987        setSelection(end);
988        String text = getText().toString().substring(start, end);
989        if (!TextUtils.isEmpty(text)) {
990            RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
991            QwertyKeyListener.markAsReplaced(editable, start, end, "");
992            CharSequence chipText = createChip(entry, false);
993            editable.replace(start, getSelectionEnd(), chipText);
994        }
995        dismissDropDown();
996    }
997
998    /**
999     * If there is a selected chip, delegate the key events
1000     * to the selected chip.
1001     */
1002    @Override
1003    public boolean onKeyDown(int keyCode, KeyEvent event) {
1004        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1005            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1006                mAlternatesPopup.dismiss();
1007            }
1008            removeChip(mSelectedChip);
1009        }
1010
1011        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
1012            return true;
1013        }
1014
1015        return super.onKeyDown(keyCode, event);
1016    }
1017
1018    // Visible for testing.
1019    /* package */ Spannable getSpannable() {
1020        return getText();
1021    }
1022
1023    private int getChipStart(RecipientChip chip) {
1024        return getSpannable().getSpanStart(chip);
1025    }
1026
1027    private int getChipEnd(RecipientChip chip) {
1028        return getSpannable().getSpanEnd(chip);
1029    }
1030
1031    /**
1032     * Instead of filtering on the entire contents of the edit box,
1033     * this subclass method filters on the range from
1034     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1035     * if the length of that range meets or exceeds {@link #getThreshold}
1036     * and makes sure that the range is not already a Chip.
1037     */
1038    @Override
1039    protected void performFiltering(CharSequence text, int keyCode) {
1040        if (enoughToFilter()) {
1041            int end = getSelectionEnd();
1042            int start = mTokenizer.findTokenStart(text, end);
1043            // If this is a RecipientChip, don't filter
1044            // on its contents.
1045            Spannable span = getSpannable();
1046            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1047            if (chips != null && chips.length > 0) {
1048                return;
1049            }
1050        }
1051        super.performFiltering(text, keyCode);
1052    }
1053
1054    private void clearSelectedChip() {
1055        if (mSelectedChip != null) {
1056            unselectChip(mSelectedChip);
1057            mSelectedChip = null;
1058        }
1059        setCursorVisible(true);
1060    }
1061
1062    /**
1063     * Monitor touch events in the RecipientEditTextView.
1064     * If the view does not have focus, any tap on the view
1065     * will just focus the view. If the view has focus, determine
1066     * if the touch target is a recipient chip. If it is and the chip
1067     * is not selected, select it and clear any other selected chips.
1068     * If it isn't, then select that chip.
1069     */
1070    @Override
1071    public boolean onTouchEvent(MotionEvent event) {
1072        if (!isFocused()) {
1073            // Ignore any chip taps until this view is focused.
1074            return super.onTouchEvent(event);
1075        }
1076        boolean handled = super.onTouchEvent(event);
1077        int action = event.getAction();
1078        boolean chipWasSelected = false;
1079        if (mSelectedChip == null) {
1080            mGestureDetector.onTouchEvent(event);
1081        }
1082        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1083            float x = event.getX();
1084            float y = event.getY();
1085            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1086            RecipientChip currentChip = findChip(offset);
1087            if (currentChip != null) {
1088                if (action == MotionEvent.ACTION_UP) {
1089                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1090                        clearSelectedChip();
1091                        mSelectedChip = selectChip(currentChip);
1092                    } else if (mSelectedChip == null) {
1093                        setSelection(getText().length());
1094                        commitDefault();
1095                        mSelectedChip = selectChip(currentChip);
1096                    } else {
1097                        onClick(mSelectedChip, offset, x, y);
1098                    }
1099                }
1100                chipWasSelected = true;
1101                handled = true;
1102            } else if (mSelectedChip != null
1103                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1104                chipWasSelected = true;
1105            }
1106        }
1107        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1108            clearSelectedChip();
1109        }
1110        return handled;
1111    }
1112
1113    private void scrollLineIntoView(int line) {
1114        if (mScrollView != null) {
1115            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1116        }
1117    }
1118
1119    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1120            int width, Context context) {
1121        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1122        int bottom = calculateOffsetFromBottom(line);
1123        // Align the alternates popup with the left side of the View,
1124        // regardless of the position of the chip tapped.
1125        alternatesPopup.setWidth(width);
1126        setEnabled(false);
1127        alternatesPopup.setAnchorView(this);
1128        alternatesPopup.setVerticalOffset(bottom);
1129        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1130        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1131        // Clear the checked item.
1132        mCheckedItem = -1;
1133        alternatesPopup.show();
1134        ListView listView = alternatesPopup.getListView();
1135        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1136        // Checked item would be -1 if the adapter has not
1137        // loaded the view that should be checked yet. The
1138        // variable will be set correctly when onCheckedItemChanged
1139        // is called in a separate thread.
1140        if (mCheckedItem != -1) {
1141            listView.setItemChecked(mCheckedItem, true);
1142            mCheckedItem = -1;
1143        }
1144    }
1145
1146    // Dismiss listener for alterns and single address popup.
1147    @Override
1148    public void onDismiss() {
1149        setEnabled(true);
1150    }
1151
1152    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1153        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1154                mAlternatesLayout, this);
1155    }
1156
1157    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1158        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1159                .getEntry());
1160    }
1161
1162    @Override
1163    public void onCheckedItemChanged(int position) {
1164        ListView listView = mAlternatesPopup.getListView();
1165        if (listView != null && listView.getCheckedItemCount() == 0) {
1166            listView.setItemChecked(position, true);
1167        }
1168        mCheckedItem = position;
1169    }
1170
1171    // TODO: This algorithm will need a lot of tweaking after more people have used
1172    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1173    // what comes before the finger.
1174    private int putOffsetInRange(int o) {
1175        int offset = o;
1176        Editable text = getText();
1177        int length = text.length();
1178        // Remove whitespace from end to find "real end"
1179        int realLength = length;
1180        for (int i = length - 1; i >= 0; i--) {
1181            if (text.charAt(i) == ' ') {
1182                realLength--;
1183            } else {
1184                break;
1185            }
1186        }
1187
1188        // If the offset is beyond or at the end of the text,
1189        // leave it alone.
1190        if (offset >= realLength) {
1191            return offset;
1192        }
1193        Editable editable = getText();
1194        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1195            // Keep walking backward!
1196            offset--;
1197        }
1198        return offset;
1199    }
1200
1201    private int findText(Editable text, int offset) {
1202        if (text.charAt(offset) != ' ') {
1203            return offset;
1204        }
1205        return -1;
1206    }
1207
1208    private RecipientChip findChip(int offset) {
1209        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1210        // Find the chip that contains this offset.
1211        for (int i = 0; i < chips.length; i++) {
1212            RecipientChip chip = chips[i];
1213            int start = getChipStart(chip);
1214            int end = getChipEnd(chip);
1215            if (offset >= start && offset <= end) {
1216                return chip;
1217            }
1218        }
1219        return null;
1220    }
1221
1222    // Visible for testing.
1223    /* package */ String createDisplayText(RecipientEntry entry) {
1224        String display = entry.getDisplayName();
1225        String address = entry.getDestination();
1226        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1227            display = null;
1228        }
1229        if (address != null) {
1230            // Tokenize out the address in case the address already
1231            // contained the username as well.
1232            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1233            if (tokenized != null && tokenized.length > 0) {
1234                address = tokenized[0].getAddress();
1235            }
1236        }
1237        Rfc822Token token = new Rfc822Token(display, address, null);
1238        String displayText = token.toString();
1239        String trimmedDisplayText = displayText.trim();
1240        int index = trimmedDisplayText.indexOf(",");
1241        return index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1242                .terminateToken(displayText) : displayText;
1243    }
1244
1245    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1246        String displayText = createDisplayText(entry);
1247        // Always leave a blank space at the end of a chip.
1248        int textLength = displayText.length()-1;
1249        SpannableString chipText = new SpannableString(displayText);
1250        int end = getSelectionEnd();
1251        int start = mTokenizer.findTokenStart(getText(), end);
1252        try {
1253            RecipientChip chip = constructChipSpan(entry, start, pressed);
1254            chipText.setSpan(chip, 0, textLength,
1255                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1256            chip.setOriginalText(chipText.toString());
1257        } catch (NullPointerException e) {
1258            Log.e(TAG, e.getMessage(), e);
1259            return null;
1260        }
1261
1262        return chipText;
1263    }
1264
1265    /**
1266     * When an item in the suggestions list has been clicked, create a chip from the
1267     * contact information of the selected item.
1268     */
1269    @Override
1270    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1271        submitItemAtPosition(position);
1272    }
1273
1274    private void submitItemAtPosition(int position) {
1275        RecipientEntry entry = createValidatedEntry(
1276                (RecipientEntry)getAdapter().getItem(position));
1277        if (entry == null) {
1278            return;
1279        }
1280        clearComposingText();
1281
1282        int end = getSelectionEnd();
1283        int start = mTokenizer.findTokenStart(getText(), end);
1284
1285        Editable editable = getText();
1286        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1287        CharSequence chip = createChip(entry, false);
1288        if (chip != null) {
1289            editable.replace(start, end, chip);
1290        }
1291        sanitizeBetween();
1292    }
1293
1294    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1295        if (item == null) {
1296            return null;
1297        }
1298        final RecipientEntry entry;
1299        // If the display name and the address are the same, or if this is a
1300        // valid contact, but the destination is invalid, then make this a fake
1301        // recipient that is editable.
1302        String destination = item.getDestination();
1303        if (TextUtils.isEmpty(item.getDisplayName())
1304                || TextUtils.equals(item.getDisplayName(), destination)
1305                || (mValidator != null && !mValidator.isValid(destination))) {
1306            entry = RecipientEntry.constructFakeEntry(destination);
1307        } else {
1308            entry = item;
1309        }
1310        return entry;
1311    }
1312
1313    /** Returns a collection of contact Id for each chip inside this View. */
1314    /* package */ Collection<Long> getContactIds() {
1315        final Set<Long> result = new HashSet<Long>();
1316        RecipientChip[] chips = getRecipients();
1317        if (chips != null) {
1318            for (RecipientChip chip : chips) {
1319                result.add(chip.getContactId());
1320            }
1321        }
1322        return result;
1323    }
1324
1325    private RecipientChip[] getRecipients() {
1326        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1327    }
1328
1329    // Visible for testing.
1330    /* package */ RecipientChip[] getSortedRecipients() {
1331        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1332                .asList(getRecipients()));
1333        final Spannable spannable = getSpannable();
1334        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1335
1336            @Override
1337            public int compare(RecipientChip first, RecipientChip second) {
1338                int firstStart = spannable.getSpanStart(first);
1339                int secondStart = spannable.getSpanStart(second);
1340                if (firstStart < secondStart) {
1341                    return -1;
1342                } else if (firstStart > secondStart) {
1343                    return 1;
1344                } else {
1345                    return 0;
1346                }
1347            }
1348        });
1349        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1350    }
1351
1352    /** Returns a collection of data Id for each chip inside this View. May be null. */
1353    /* package */ Collection<Long> getDataIds() {
1354        final Set<Long> result = new HashSet<Long>();
1355        RecipientChip [] chips = getRecipients();
1356        if (chips != null) {
1357            for (RecipientChip chip : chips) {
1358                result.add(chip.getDataId());
1359            }
1360        }
1361        return result;
1362    }
1363
1364
1365    @Override
1366    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1367        return false;
1368    }
1369
1370    @Override
1371    public void onDestroyActionMode(ActionMode mode) {
1372    }
1373
1374    @Override
1375    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1376        return false;
1377    }
1378
1379    /**
1380     * No chips are selectable.
1381     */
1382    @Override
1383    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1384        return false;
1385    }
1386
1387
1388    private ImageSpan getMoreChip() {
1389        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1390                MoreImageSpan.class);
1391        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1392    }
1393
1394    /**
1395     * Create the more chip. The more chip is text that replaces any chips that
1396     * do not fit in the pre-defined available space when the
1397     * RecipientEditTextView loses focus.
1398     */
1399    private void createMoreChip() {
1400        if (!mShouldShrink) {
1401            return;
1402        }
1403
1404        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1405        if (tempMore.length > 0) {
1406            getSpannable().removeSpan(tempMore[0]);
1407        }
1408        RecipientChip[] recipients = getSortedRecipients();
1409        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1410            mMoreChip = null;
1411            return;
1412        }
1413        Spannable spannable = getSpannable();
1414        int numRecipients = recipients.length;
1415        int overage = numRecipients - CHIP_LIMIT;
1416        String moreText = String.format(mMoreItem.getText().toString(), overage);
1417        TextPaint morePaint = new TextPaint(getPaint());
1418        morePaint.setTextSize(mMoreItem.getTextSize());
1419        morePaint.setColor(mMoreItem.getCurrentTextColor());
1420        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1421                + mMoreItem.getPaddingRight();
1422        int height = getLineHeight();
1423        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1424        Canvas canvas = new Canvas(drawable);
1425        int adjustedHeight = height;
1426        Layout layout = getLayout();
1427        if (layout != null) {
1428            adjustedHeight -= layout.getLineDescent(0);
1429        }
1430        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1431
1432        Drawable result = new BitmapDrawable(getResources(), drawable);
1433        result.setBounds(0, 0, width, height);
1434        MoreImageSpan moreSpan = new MoreImageSpan(result);
1435        // Remove the overage chips.
1436        if (recipients == null || recipients.length == 0) {
1437            Log.w(TAG,
1438                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1439            mMoreChip = null;
1440            return;
1441        }
1442        mRemovedSpans = new ArrayList<RecipientChip>();
1443        int totalReplaceStart = 0;
1444        int totalReplaceEnd = 0;
1445        Editable text = getText();
1446        for (int i = numRecipients - overage; i < recipients.length; i++) {
1447            mRemovedSpans.add(recipients[i]);
1448            if (i == numRecipients - overage) {
1449                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1450            }
1451            if (i == recipients.length - 1) {
1452                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1453            }
1454            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1455                int spanStart = spannable.getSpanStart(recipients[i]);
1456                int spanEnd = spannable.getSpanEnd(recipients[i]);
1457                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1458            }
1459            spannable.removeSpan(recipients[i]);
1460        }
1461        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1462        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1463        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1464        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1465        text.replace(start, end, chipText);
1466        mMoreChip = moreSpan;
1467    }
1468
1469    /**
1470     * Replace the more chip, if it exists, with all of the recipient chips it had
1471     * replaced when the RecipientEditTextView gains focus.
1472     */
1473    private void removeMoreChip() {
1474        if (mMoreChip != null) {
1475            Spannable span = getSpannable();
1476            span.removeSpan(mMoreChip);
1477            mMoreChip = null;
1478            // Re-add the spans that were removed.
1479            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1480                // Recreate each removed span.
1481                RecipientChip[] recipients = getSortedRecipients();
1482                // Start the search for tokens after the last currently visible
1483                // chip.
1484                if (recipients == null || recipients.length == 0) {
1485                    return;
1486                }
1487                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1488                Editable editable = getText();
1489                for (RecipientChip chip : mRemovedSpans) {
1490                    int chipStart;
1491                    int chipEnd;
1492                    String token;
1493                    // Need to find the location of the chip, again.
1494                    token = (String) chip.getOriginalText();
1495                    // As we find the matching recipient for the remove spans,
1496                    // reduce the size of the string we need to search.
1497                    // That way, if there are duplicates, we always find the correct
1498                    // recipient.
1499                    chipStart = editable.toString().indexOf(token, end);
1500                    // -1 for the space!
1501                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1502                    // Only set the span if we found a matching token.
1503                    if (chipStart != -1) {
1504                        editable.setSpan(chip, chipStart, chipEnd,
1505                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1506                    }
1507                }
1508                mRemovedSpans.clear();
1509            }
1510        }
1511    }
1512
1513    /**
1514     * Show specified chip as selected. If the RecipientChip is just an email address,
1515     * selecting the chip will take the contents of the chip and place it at
1516     * the end of the RecipientEditTextView for inline editing. If the
1517     * RecipientChip is a complete contact, then selecting the chip
1518     * will change the background color of the chip, show the delete icon,
1519     * and a popup window with the address in use highlighted and any other
1520     * alternate addresses for the contact.
1521     * @param currentChip Chip to select.
1522     * @return A RecipientChip in the selected state or null if the chip
1523     * just contained an email address.
1524     */
1525    public RecipientChip selectChip(RecipientChip currentChip) {
1526        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1527            CharSequence text = currentChip.getValue();
1528            Editable editable = getText();
1529            removeChip(currentChip);
1530            editable.append(text);
1531            setCursorVisible(true);
1532            setSelection(editable.length());
1533            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1534        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1535            int start = getChipStart(currentChip);
1536            int end = getChipEnd(currentChip);
1537            getSpannable().removeSpan(currentChip);
1538            RecipientChip newChip;
1539            try {
1540                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1541            } catch (NullPointerException e) {
1542                Log.e(TAG, e.getMessage(), e);
1543                return null;
1544            }
1545            Editable editable = getText();
1546            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1547            if (start == -1 || end == -1) {
1548                Log.d(TAG, "The chip being selected no longer exists but should.");
1549            } else {
1550                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1551            }
1552            newChip.setSelected(true);
1553            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1554                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1555            }
1556            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1557            setCursorVisible(false);
1558            return newChip;
1559        } else {
1560            int start = getChipStart(currentChip);
1561            int end = getChipEnd(currentChip);
1562            getSpannable().removeSpan(currentChip);
1563            RecipientChip newChip;
1564            try {
1565                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1566            } catch (NullPointerException e) {
1567                Log.e(TAG, e.getMessage(), e);
1568                return null;
1569            }
1570            Editable editable = getText();
1571            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1572            if (start == -1 || end == -1) {
1573                Log.d(TAG, "The chip being selected no longer exists but should.");
1574            } else {
1575                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1576            }
1577            newChip.setSelected(true);
1578            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1579                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1580            }
1581            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1582            setCursorVisible(false);
1583            return newChip;
1584        }
1585    }
1586
1587
1588    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1589            int width, Context context) {
1590        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1591        int bottom = calculateOffsetFromBottom(line);
1592        // Align the alternates popup with the left side of the View,
1593        // regardless of the position of the chip tapped.
1594        setEnabled(false);
1595        popup.setWidth(width);
1596        popup.setAnchorView(this);
1597        popup.setVerticalOffset(bottom);
1598        popup.setAdapter(createSingleAddressAdapter(currentChip));
1599        popup.setOnItemClickListener(new OnItemClickListener() {
1600            @Override
1601            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1602                unselectChip(currentChip);
1603                popup.dismiss();
1604            }
1605        });
1606        popup.show();
1607        ListView listView = popup.getListView();
1608        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1609        listView.setItemChecked(0, true);
1610    }
1611
1612    /**
1613     * Remove selection from this chip. Unselecting a RecipientChip will render
1614     * the chip without a delete icon and with an unfocused background. This
1615     * is called when the RecipientChip no longer has focus.
1616     */
1617    public void unselectChip(RecipientChip chip) {
1618        int start = getChipStart(chip);
1619        int end = getChipEnd(chip);
1620        Editable editable = getText();
1621        mSelectedChip = null;
1622        if (start == -1 || end == -1) {
1623            Log.w(TAG,
1624                    "The chip doesn't exist or may be a chip a user was editing");
1625            setSelection(editable.length());
1626            commitDefault();
1627        } else {
1628            getSpannable().removeSpan(chip);
1629            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1630            editable.removeSpan(chip);
1631            try {
1632                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1633                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1634            } catch (NullPointerException e) {
1635                Log.e(TAG, e.getMessage(), e);
1636            }
1637        }
1638        setCursorVisible(true);
1639        setSelection(editable.length());
1640        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1641            mAlternatesPopup.dismiss();
1642        }
1643    }
1644
1645    /**
1646     * Return whether this chip contains the position passed in.
1647     */
1648    public boolean matchesChip(RecipientChip chip, int offset) {
1649        int start = getChipStart(chip);
1650        int end = getChipEnd(chip);
1651        if (start == -1 || end == -1) {
1652            return false;
1653        }
1654        return (offset >= start && offset <= end);
1655    }
1656
1657
1658    /**
1659     * Return whether a touch event was inside the delete target of
1660     * a selected chip. It is in the delete target if:
1661     * 1) the x and y points of the event are within the
1662     * delete assset.
1663     * 2) the point tapped would have caused a cursor to appear
1664     * right after the selected chip.
1665     * @return boolean
1666     */
1667    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1668        // Figure out the bounds of this chip and whether or not
1669        // the user clicked in the X portion.
1670        return chip.isSelected() && offset == getChipEnd(chip);
1671    }
1672
1673    /**
1674     * Remove the chip and any text associated with it from the RecipientEditTextView.
1675     */
1676    private void removeChip(RecipientChip chip) {
1677        Spannable spannable = getSpannable();
1678        int spanStart = spannable.getSpanStart(chip);
1679        int spanEnd = spannable.getSpanEnd(chip);
1680        Editable text = getText();
1681        int toDelete = spanEnd;
1682        boolean wasSelected = chip == mSelectedChip;
1683        // Clear that there is a selected chip before updating any text.
1684        if (wasSelected) {
1685            mSelectedChip = null;
1686        }
1687        // Always remove trailing spaces when removing a chip.
1688        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1689            toDelete++;
1690        }
1691        spannable.removeSpan(chip);
1692        text.delete(spanStart, toDelete);
1693        if (wasSelected) {
1694            clearSelectedChip();
1695        }
1696    }
1697
1698    /**
1699     * Replace this currently selected chip with a new chip
1700     * that uses the contact data provided.
1701     */
1702    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1703        boolean wasSelected = chip == mSelectedChip;
1704        if (wasSelected) {
1705            mSelectedChip = null;
1706        }
1707        int start = getChipStart(chip);
1708        int end = getChipEnd(chip);
1709        getSpannable().removeSpan(chip);
1710        Editable editable = getText();
1711        CharSequence chipText = createChip(entry, false);
1712        if (start == -1 || end == -1) {
1713            Log.e(TAG, "The chip to replace does not exist but should.");
1714            editable.insert(0, chipText);
1715        } else {
1716            // There may be a space to replace with this chip's new associated
1717            // space. Check for it.
1718            int toReplace = end;
1719            while (toReplace >= 0 && toReplace < editable.length()
1720                    && editable.charAt(toReplace) == ' ') {
1721                toReplace++;
1722            }
1723            editable.replace(start, toReplace, chipText);
1724        }
1725        setCursorVisible(true);
1726        if (wasSelected) {
1727            clearSelectedChip();
1728        }
1729    }
1730
1731    /**
1732     * Handle click events for a chip. When a selected chip receives a click
1733     * event, see if that event was in the delete icon. If so, delete it.
1734     * Otherwise, unselect the chip.
1735     */
1736    public void onClick(RecipientChip chip, int offset, float x, float y) {
1737        if (chip.isSelected()) {
1738            if (isInDelete(chip, offset, x, y)) {
1739                removeChip(chip);
1740            } else {
1741                clearSelectedChip();
1742            }
1743        }
1744    }
1745
1746    private boolean chipsPending() {
1747        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1748    }
1749
1750    @Override
1751    public void removeTextChangedListener(TextWatcher watcher) {
1752        mTextWatcher = null;
1753        super.removeTextChangedListener(watcher);
1754    }
1755
1756    private class RecipientTextWatcher implements TextWatcher {
1757        @Override
1758        public void afterTextChanged(Editable s) {
1759            // If the text has been set to null or empty, make sure we remove
1760            // all the spans we applied.
1761            if (TextUtils.isEmpty(s)) {
1762                // Remove all the chips spans.
1763                Spannable spannable = getSpannable();
1764                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1765                        RecipientChip.class);
1766                for (RecipientChip chip : chips) {
1767                    spannable.removeSpan(chip);
1768                }
1769                if (mMoreChip != null) {
1770                    spannable.removeSpan(mMoreChip);
1771                }
1772                return;
1773            }
1774            // Get whether there are any recipients pending addition to the
1775            // view. If there are, don't do anything in the text watcher.
1776            if (chipsPending()) {
1777                return;
1778            }
1779            // If the user is editing a chip, don't clear it.
1780            if (mSelectedChip != null
1781                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
1782                setCursorVisible(true);
1783                setSelection(getText().length());
1784                clearSelectedChip();
1785            }
1786            int length = s.length();
1787            // Make sure there is content there to parse and that it is
1788            // not just the commit character.
1789            if (length > 1) {
1790                char last;
1791                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1792                int len = length() - 1;
1793                if (end != len) {
1794                    last = s.charAt(end);
1795                } else {
1796                    last = s.charAt(len);
1797                }
1798                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1799                    commitByCharacter();
1800                } else if (last == COMMIT_CHAR_SPACE) {
1801                    // Check if this is a valid email address. If it is,
1802                    // commit it.
1803                    String text = getText().toString();
1804                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1805                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1806                            tokenStart));
1807                    if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
1808                        commitByCharacter();
1809                    }
1810                }
1811            }
1812        }
1813
1814        @Override
1815        public void onTextChanged(CharSequence s, int start, int before, int count) {
1816            // Do nothing.
1817        }
1818
1819        @Override
1820        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1821            // Do nothing.
1822        }
1823    }
1824
1825    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1826        private RecipientChip createFreeChip(RecipientEntry entry) {
1827            try {
1828                return constructChipSpan(entry, -1, false);
1829            } catch (NullPointerException e) {
1830                Log.e(TAG, e.getMessage(), e);
1831                return null;
1832            }
1833        }
1834
1835        @Override
1836        protected Void doInBackground(Void... params) {
1837            if (mIndividualReplacements != null) {
1838                mIndividualReplacements.cancel(true);
1839            }
1840            // For each chip in the list, look up the matching contact.
1841            // If there is a match, replace that chip with the matching
1842            // chip.
1843            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1844            RecipientChip[] existingChips = getSortedRecipients();
1845            for (int i = 0; i < existingChips.length; i++) {
1846                originalRecipients.add(existingChips[i]);
1847            }
1848            if (mRemovedSpans != null) {
1849                originalRecipients.addAll(mRemovedSpans);
1850            }
1851            String[] addresses = new String[originalRecipients.size()];
1852            for (int i = 0; i < originalRecipients.size(); i++) {
1853                addresses[i] = createDisplayText(originalRecipients.get(i).getEntry());
1854            }
1855            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1856                    .getMatchingRecipients(getContext(), addresses);
1857            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1858            for (final RecipientChip temp : originalRecipients) {
1859                RecipientEntry entry = null;
1860                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1861                        && getSpannable().getSpanStart(temp) != -1) {
1862                    // Replace this.
1863                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
1864                            .getDestination())));
1865                }
1866                if (entry != null) {
1867                    replacements.add(createFreeChip(entry));
1868                } else {
1869                    replacements.add(temp);
1870                }
1871            }
1872            if (replacements != null && replacements.size() > 0) {
1873                mHandler.post(new Runnable() {
1874                    @Override
1875                    public void run() {
1876                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1877                                .toString());
1878                        Editable oldText = getText();
1879                        int start, end;
1880                        int i = 0;
1881                        for (RecipientChip chip : originalRecipients) {
1882                            start = oldText.getSpanStart(chip);
1883                            if (start != -1) {
1884                                end = oldText.getSpanEnd(chip);
1885                                text.removeSpan(chip);
1886                                // Leave a spot for the space!
1887                                RecipientChip replacement = replacements.get(i);
1888                                text.setSpan(replacement, start, end,
1889                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1890                                replacement.setOriginalText(text.toString().substring(start, end));
1891                            }
1892                            i++;
1893                        }
1894                        Editable editable = getText();
1895                        editable.clear();
1896                        editable.insert(0, text);
1897                        originalRecipients.clear();
1898                    }
1899                });
1900            }
1901            return null;
1902        }
1903    }
1904
1905    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1906        @SuppressWarnings("unchecked")
1907        @Override
1908        protected Void doInBackground(Object... params) {
1909            // For each chip in the list, look up the matching contact.
1910            // If there is a match, replace that chip with the matching
1911            // chip.
1912            final ArrayList<RecipientChip> originalRecipients =
1913                (ArrayList<RecipientChip>) params[0];
1914            String[] addresses = new String[originalRecipients.size()];
1915            for (int i = 0; i < originalRecipients.size(); i++) {
1916                addresses[i] = createDisplayText(originalRecipients.get(i).getEntry());
1917            }
1918            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1919                    .getMatchingRecipients(getContext(), addresses);
1920            for (final RecipientChip temp : originalRecipients) {
1921                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1922                        && getSpannable().getSpanStart(temp) != -1) {
1923                    // Replace this.
1924                    final RecipientEntry entry = createValidatedEntry(entries
1925                            .get(tokenizeAddress(temp.getEntry().getDestination())));
1926                    if (entry != null) {
1927                        mHandler.post(new Runnable() {
1928                            @Override
1929                            public void run() {
1930                                replaceChip(temp, entry);
1931                            }
1932                        });
1933                    }
1934                }
1935            }
1936            return null;
1937        }
1938    }
1939
1940
1941    /**
1942     * MoreImageSpan is a simple class created for tracking the existence of a
1943     * more chip across activity restarts/
1944     */
1945    private class MoreImageSpan extends ImageSpan {
1946        public MoreImageSpan(Drawable b) {
1947            super(b);
1948        }
1949    }
1950
1951    @Override
1952    public boolean onDown(MotionEvent e) {
1953        return false;
1954    }
1955
1956    @Override
1957    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
1958        // Do nothing.
1959        return false;
1960    }
1961
1962    @Override
1963    public void onLongPress(MotionEvent event) {
1964        if (mSelectedChip != null) {
1965            return;
1966        }
1967        float x = event.getX();
1968        float y = event.getY();
1969        int offset = putOffsetInRange(getOffsetForPosition(x, y));
1970        RecipientChip currentChip = findChip(offset);
1971        if (currentChip != null) {
1972            // Copy the selected chip email address.
1973            showCopyDialog(currentChip.getEntry().getDestination());
1974        }
1975    }
1976
1977    private void showCopyDialog(final String address) {
1978        mCopyAddress = address;
1979        mCopyDialog.setTitle(address);
1980        mCopyDialog.setContentView(mCopyViewRes);
1981        mCopyDialog.setCancelable(true);
1982        mCopyDialog.setCanceledOnTouchOutside(true);
1983        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
1984        mCopyDialog.setOnDismissListener(this);
1985        mCopyDialog.show();
1986    }
1987
1988    @Override
1989    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
1990        // Do nothing.
1991        return false;
1992    }
1993
1994    @Override
1995    public void onShowPress(MotionEvent e) {
1996        // Do nothing.
1997    }
1998
1999    @Override
2000    public boolean onSingleTapUp(MotionEvent e) {
2001        // Do nothing.
2002        return false;
2003    }
2004
2005    @Override
2006    public void onDismiss(DialogInterface dialog) {
2007        mCopyAddress = null;
2008    }
2009
2010    @Override
2011    public void onClick(View v) {
2012        // Copy this to the clipboard.
2013        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2014                Context.CLIPBOARD_SERVICE);
2015        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2016        mCopyDialog.dismiss();
2017    }
2018}
2019