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