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