Example usage for android.text SpannableString toString

List of usage examples for android.text SpannableString toString

Introduction

In this page you can find the example usage for android.text SpannableString toString.

Prototype

public String toString();

Source Link

Document

Returns a string containing the characters in this sequence in the same order as this sequence.

Usage

From source file:com.android.mail.utils.NotificationUtils.java

private static SpannableStringBuilder ellipsizeStyledSenders(final Context context,
        ArrayList<SpannableString> styledSenders) {
    if (sSendersSplitToken == null) {
        sSendersSplitToken = context.getString(R.string.senders_split_token);
        sElidedPaddingToken = context.getString(R.string.elided_padding_token);
    }//from  ww w  .  jav a  2  s .  com

    SpannableStringBuilder builder = new SpannableStringBuilder();
    SpannableString prevSender = null;
    for (SpannableString sender : styledSenders) {
        if (sender == null) {
            LogUtils.e(LOG_TAG, "null sender iterating over styledSenders");
            continue;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        if (SendersView.sElidedString.equals(sender.toString())) {
            prevSender = sender;
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            prevSender = sender;
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            prevSender = sender;
        }
        builder.append(sender);
    }
    return builder;
}

From source file:ru.valle.btc.MainActivity.java

private CharSequence getPrivateKeyTypeLabel(final KeyPair keyPair) {
    int typeWithCompression = keyPair.privateKey.type == BTCUtils.PrivateKeyInfo.TYPE_BRAIN_WALLET
            && keyPair.privateKey.isPublicKeyCompressed ? keyPair.privateKey.type + 1 : keyPair.privateKey.type;
    CharSequence keyType = getResources().getTextArray(R.array.private_keys_types)[typeWithCompression];
    SpannableString keyTypeLabel = new SpannableString(getString(R.string.private_key_type, keyType));
    int keyTypeStart = keyTypeLabel.toString().indexOf(keyType.toString());
    keyTypeLabel.setSpan(new StyleSpan(Typeface.BOLD), keyTypeStart, keyTypeStart + keyType.length(),
            SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
    if (keyPair.privateKey.type == BTCUtils.PrivateKeyInfo.TYPE_BRAIN_WALLET) {
        String compressionStrToSpan = keyType.toString().substring(keyType.toString().indexOf(',') + 2);
        int start = keyTypeLabel.toString().indexOf(compressionStrToSpan);
        if (start >= 0) {

            ClickableSpan switchPublicKeyCompressionSpan = new ClickableSpan() {
                @Override/*from  w  w w.  ja  va 2  s.c o  m*/
                public void onClick(View widget) {
                    cancelAllRunningTasks();
                    switchingCompressionTypeTask = new AsyncTask<Void, Void, KeyPair>() {

                        @Override
                        protected KeyPair doInBackground(Void... params) {
                            return new KeyPair(new BTCUtils.PrivateKeyInfo(keyPair.privateKey.type,
                                    keyPair.privateKey.privateKeyEncoded, keyPair.privateKey.privateKeyDecoded,
                                    !keyPair.privateKey.isPublicKeyCompressed));
                        }

                        @Override
                        protected void onPostExecute(KeyPair keyPair) {
                            switchingCompressionTypeTask = null;
                            onKeyPairModify(false, keyPair);
                        }
                    };
                    switchingCompressionTypeTask.execute();
                }
            };
            keyTypeLabel.setSpan(switchPublicKeyCompressionSpan, start, start + compressionStrToSpan.length(),
                    SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
        }
    }
    return keyTypeLabel;
}

From source file:com.android.mail.browse.ConversationItemView.java

SpannableStringBuilder elideParticipants(List<SpannableString> parts) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    float totalWidth = 0;
    boolean ellipsize = false;
    float width;//from   w w  w.ja va2  s  .  co m
    boolean skipToHeader = false;

    // start with "To: " if we're showing recipients
    if (mDisplayedFolder.shouldShowRecipients() && !parts.isEmpty()) {
        final SpannableString toHeader = SendersView.getFormattedToHeader();
        CharacterStyle[] spans = toHeader.getSpans(0, toHeader.length(), CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        totalWidth += sPaint.measureText(toHeader.toString());
        builder.append(toHeader);
        skipToHeader = true;
    }

    final SpannableStringBuilder messageInfoString = mHeader.messageInfoString;
    if (!TextUtils.isEmpty(messageInfoString)) {
        CharacterStyle[] spans = messageInfoString.getSpans(0, messageInfoString.length(),
                CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // Paint the message info string to see if we lose space.
        float messageInfoWidth = sPaint.measureText(messageInfoString.toString());
        totalWidth += messageInfoWidth;
    }
    SpannableString prevSender = null;
    SpannableString ellipsizedText;
    for (SpannableString sender : parts) {
        // There may be null sender strings if there were dupes we had to remove.
        if (sender == null) {
            continue;
        }
        // No more width available, we'll only show fixed fragments.
        if (ellipsize) {
            break;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        // There is only 1 character style span.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // If there are already senders present in this string, we need to
        // make sure we prepend the dividing token
        if (SendersView.sElidedString.equals(sender.toString())) {
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (!skipToHeader && builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            skipToHeader = false;
        }
        prevSender = sender;

        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // Measure the width of the current sender and make sure we have space
        width = (int) sPaint.measureText(sender.toString());
        if (width + totalWidth > mSendersWidth) {
            // The text is too long, new line won't help. We have to
            // ellipsize text.
            ellipsize = true;
            width = mSendersWidth - totalWidth; // ellipsis width?
            ellipsizedText = copyStyles(spans, TextUtils.ellipsize(sender, sPaint, width, TruncateAt.END));
            width = (int) sPaint.measureText(ellipsizedText.toString());
        } else {
            ellipsizedText = null;
        }
        totalWidth += width;

        final CharSequence fragmentDisplayText;
        if (ellipsizedText != null) {
            fragmentDisplayText = ellipsizedText;
        } else {
            fragmentDisplayText = sender;
        }
        builder.append(fragmentDisplayText);
    }
    mHeader.styledMessageInfoStringOffset = builder.length();
    if (!TextUtils.isEmpty(messageInfoString)) {
        builder.append(messageInfoString);
    }
    return builder;
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * handle the receipt of suggestions from the spell checker
 * colour the text in the editor as required
 * pass information to the keyboard view so it can draw the colour bar
 * initiate audio and haptic feedback as required
 *///  ww  w. j a  v  a2 s.c  o  m
@Override
public void onGetSuggestions(SuggestionsInfo[] results) {
    // TODO Auto-generated method stub
    int colortype = -1;
    final StringBuilder sb = new StringBuilder();

    if (updateSuggestionList) {
        updateSuggestionList = false;
        ArrayList<String> s = new ArrayList<String>();
        for (int i = 0; i < results.length; ++i) {
            final int length = results[i].getSuggestionsCount();
            for (int j = 0; j < length; ++j) {
                s.add(results[i].getSuggestionAt(j));
            }
        }
        updateSuggestionListWithSpellChecker(s);
    } else {

        for (int i = 0; i < results.length; ++i) {
            // Returned suggestions are contained in SuggestionsInfo

            final int len = results[i].getSuggestionsCount();
            sb.append("Suggestion Attribs: " + results[i].getSuggestionsAttributes());
            if ((results[i].getSuggestionsAttributes()
                    & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) == SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) {
                sb.append("The word was found in the dictionary\n");
                mInputView.wordcompletedtype = 3;
            } else {

                if ((results[i].getSuggestionsAttributes()
                        & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) == SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) {
                    if ((results[i].getSuggestionsAttributes()
                            & SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) == SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) {
                        colortype = 1; //yellow
                        mInputView.wordcompletedtype = 1;
                        sb.append("There are strong candidates for this word\n");
                        currentSession.nLowErrors++;
                    } else {
                        colortype = 2; //red
                        mInputView.wordcompletedtype = 2;
                        sb.append("The word looks like a typo\n");
                        currentSession.nHighErrors++;

                    }
                }

            }

            sb.append("\n--These are the suggestions--\n");
            for (int j = 0; j < len; ++j) {
                sb.append("," + results[i].getSuggestionAt(j));
            }
            sb.append(" (" + len + ")");
        }
        //Log.i("Spelling suggestions", sb.toString());

        //this comes after a word separator, hence just add 1 to the cursor
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        SpannableString text = new SpannableString(mComposingTemp);

        if (sharedPrefs.getBoolean("highlightwords", true)) {
            switch (colortype) {
            case 1:
                text.setSpan(new BackgroundColorSpan(small_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 2:
                text.setSpan(new BackgroundColorSpan(big_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            default:
                break;
            }
        }

        if (sharedPrefs.getBoolean("autocorrect", true) && mInputView.wordcompletedtype == 1) //handle autocorrection
        {
            SpannableString autoc = autocorrect(results);
            autocorrected_words.put(autoc.toString(), text.toString()); //autocorrected word, original input
            //Log.i("Autocorrecting","Key= "+autoc.toString()+", Value= "+text.toString());
            text = autoc;
            if (sharedPrefs.getBoolean("highlightwords", true))
                text.setSpan(new BackgroundColorSpan(autocorrect), 0, text.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mInputView.wordcompletedtype = 4;
        } else //autocorrection is turned off
        {
            if (!sharedPrefs.getBoolean("autocorrect", true) && colortype >= 1) //a mistake word
            {
                //Log.i("OnGetSentenceSuggestions","Key= "+text.toString()+", Value= "+text.toString());
                //no autocorrects, just put the word in and itself as the replacement
                autocorrected_words.put(text.toString(), text.toString());
            }
        }

        if (sharedPrefs.getBoolean("vibrator", false)) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            final int on_time = Integer.parseInt(sharedPrefs.getString("shortvibe", "35"));

            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                // Vibrate for 300 milliseconds
                v.vibrate(on_time);
                break;
            case 2: //big err
                //v.vibrate(Integer.parseInt(sharedPrefs.getString("longvibe", "300")));
                v.vibrate(new long[] { 0, on_time, 200, on_time }, -1);
                break;
            case 4: //autocorr
                v.vibrate(on_time);
                break;
            default:
                break;

            }
        }

        if (sharedPrefs.getBoolean("audio", false)) {
            final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            case 2: //big err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
                break;
            case 4: //autocorr
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            default:
                break;

            }
        }

        mInputView.invalidateAllKeys();
        ic.commitText(text, 1);
        sendKey(wordSeparatorKeyCode);
        coreEngine.resetCoreString();
        updateCandidates();
    }

}

From source file:org.de.jmg.learn._MainActivity.java

public void getVokabel(final boolean showBeds, boolean LoadNext, boolean requestFocusEdWord, boolean DontPrompt)
        throws Exception {

    if (iv != null) {
        iv.setVisibility(View.GONE);
    }/*from w w  w .  ja v a 2s. c o m*/
    if (iv2 != null)
        iv2.setVisibility(View.GONE);
    try {
        if (_btnRight == null)
            return;
        EndEdit(DontPrompt);
        setBtnsEnabled(true);
        if (showBeds && _vok.getIndex() >= 1) {
            _btnRight.setEnabled(true);
            _btnWrong.setEnabled(true);
            _btnEdit.setEnabled(true);
            _btnSkip.setEnabled(true);
            _btnView.setEnabled(true);
        } else {
            _btnRight.setEnabled(false);
            _btnWrong.setEnabled(false);
            if (_vok.getIndex() < 1) {
                _btnEdit.setEnabled(false);
                _btnSkip.setEnabled(false);
                _btnView.setEnabled(false);
            }
        }
        if (LoadNext)
            _vok.setLernIndex((short) (_vok.getLernIndex() + 1));

        View v;
        TextView t;
        String txtBed = getString(R.string.cloze);

        if (showBeds) {
            v = findViewById(R.id.txtMeaning1);
            t = (TextView) v;
            assert t != null;
            t.setText(lib.getSpanableString(_vok.getBedeutung1()));
            txtBed = t.getText().toString();
        }

        v = findViewById(R.id.word);
        t = (TextView) v;
        assert t != null;
        String txtWord = getString(R.string.cloze);
        if (!_vok.reverse || showBeds) {
            t.setText(lib.getSpanableString(_vok.getWort()), TextView.BufferType.SPANNABLE);
            txtWord = t.getText().toString();
            txtWord = replaceClozes(txtWord, txtBed);
            speak(txtWord, _vok.getLangWord(), "word", true);
        } else {
            t.setText("");
        }

        if (_vok.getSprache() == EnumSprachen.Hebrew || _vok.getSprache() == EnumSprachen.Griechisch
                || (_vok.getFontWort().getName().equalsIgnoreCase("Cardo"))) {
            t.setTypeface(_vok.TypefaceCardo);
            _txtedWord.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
            _txtedWord.setTypeface(Typeface.DEFAULT);
        }
        t.scrollTo(0, 0);

        v = findViewById(R.id.Comment);
        t = (TextView) v;
        assert t != null;
        t.setVisibility(View.VISIBLE);

        SpannableString tspanKom = lib.getSpanableString(_vok.getKommentar());
        URLSpan[] urlSpans = tspanKom.getSpans(0, tspanKom.length(), URLSpan.class);
        for (final URLSpan span : urlSpans) {
            int start = tspanKom.getSpanStart(span);
            int end = tspanKom.getSpanEnd(span);
            String txt = tspanKom.toString().substring(start, end);
            if (txtIsPicture(txt)) {
                tspanKom.removeSpan(span);
                tspanKom.setSpan(new urlclickablespan(span.getURL()) {
                    @Override
                    public void onClick(View widget) {
                        Bitmap b;
                        try {
                            b = lib.downloadpicture(this.url);
                        } catch (Exception ex) {
                            b = null;
                        }
                        if (b != null) {
                            if (iv == null) {
                                iv = new ImageView(context);
                                SetTouchListener(iv);
                            }
                            b = resizeBM(b);
                            iv.setImageBitmap(b);
                            if (iv.getParent() == null) {
                                try {
                                    LayoutParams p = _txtMeaning1.getLayoutParams();
                                    //p.width = LayoutParams.WRAP_CONTENT;
                                    //p.height = LayoutParams.WRAP_CONTENT;
                                    rellayoutMain.addView(iv, p);
                                } catch (Exception ex) {
                                    Log.e("addImageView", ex.getMessage(), ex);
                                }
                            } else {
                                Log.d("ImageView", "exists");
                            }
                            _txtMeaning1.setVisibility(View.GONE);
                            iv.setVisibility(View.VISIBLE);
                        }
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        t.setText(tspanKom, TextView.BufferType.SPANNABLE);

        if (_vok.getSprache() == EnumSprachen.Hebrew || _vok.getSprache() == EnumSprachen.Griechisch
                || (_vok.getFontKom().getName().equalsIgnoreCase("Cardo"))) {
            t.setTypeface(_vok.TypefaceCardo);
            _txtedKom.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
            _txtedKom.setTypeface(Typeface.DEFAULT);
        }
        if (_isSmallDevice && libString.IsNullOrEmpty(t.getText().toString())) {
            t.setVisibility(View.GONE);
        } else {
            t.setVisibility(View.VISIBLE);
        }
        t.scrollTo(0, 0);

        v = findViewById(R.id.txtMeaning1);
        t = (TextView) v;
        assert t != null;
        if (!libString.IsNullOrEmpty(_vok.getBedeutung2())) {
            t.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        }
        if (_vok.reverse || showBeds) {
            SpannableString tspan = lib.getSpanableString(_vok.getBedeutung1());
            //final String picname = _main.getString(R.string.picture);
            t.setVisibility(View.VISIBLE);
            if (txtIsPicture(tspan.toString())) {
                URLSpan urlspn[] = tspan.getSpans(0, tspan.length(), URLSpan.class);
                for (URLSpan url : urlspn) {
                    Bitmap b;
                    try {
                        b = lib.downloadpicture(url.getURL());
                    } catch (Exception ex) {
                        b = null;
                    }
                    if (b != null) {
                        if (iv == null) {
                            iv = new ImageView(context);
                            SetTouchListener(iv);
                        }
                        b = resizeBM(b);
                        iv.setImageBitmap(b);
                        if (iv.getParent() == null) {
                            try {
                                LayoutParams p = t.getLayoutParams();
                                //p.width = LayoutParams.WRAP_CONTENT;
                                //p.height = LayoutParams.WRAP_CONTENT;
                                rellayoutMain.addView(iv, p);
                            } catch (Exception ex) {
                                Log.e("Imagview", ex.getMessage(), ex);
                            }
                        } else {
                            Log.d("ImageView", "exists");
                        }
                        t.setVisibility(View.GONE);
                        iv.setVisibility(View.VISIBLE);
                    }
                }

            } else {
                // iv.setVisibility(View.GONE);
                t.setVisibility(View.VISIBLE);
            }

            t.setText(tspan);
        } else {
            t.setText(Vokabel.getComment(_vok.getBedeutung1()));
        }
        if (_vok.reverse || showBeds) {
            String txt = t.getText().toString();
            txt = replaceClozes(txt, txtWord);
            speak(txt, _vok.getLangMeaning(), "meaning1", _vok.reverse);
        }
        if (_vok.getFontBed().getName().equalsIgnoreCase("Cardo")) {
            t.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
        }
        t.setOnFocusChangeListener(FocusListenerMeaning1);
        t.scrollTo(0, 0);

        v = findViewById(R.id.txtMeaning2);
        t = (TextView) v;
        assert t != null;
        t.setText((_vok.reverse || showBeds ? _vok.getBedeutung2() : Vokabel.getComment(_vok.getBedeutung2())));
        if (_vok.getFontBed().getName().equalsIgnoreCase("Cardo")) {
            t.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
        }
        if (libString.IsNullOrEmpty(_vok.getBedeutung2()) || _vok.getCardMode()) {
            t.setVisibility(View.GONE);
            _txtMeaning1.setImeOptions(EditorInfo.IME_ACTION_DONE);
        } else {
            t.setVisibility(View.VISIBLE);
            _txtMeaning1.setImeOptions(EditorInfo.IME_ACTION_NEXT);
            if (_vok.reverse || showBeds) {
                String txt = t.getText().toString();
                //if (txtWord != null)
                //   txt = txt.replaceAll("_{2,}", txtWord).replaceAll("\\.{4,}", txtWord);
                speak(txt, _vok.getLangMeaning(), "meaning2");
            }
        }

        v = findViewById(R.id.txtMeaning3);
        t = (TextView) v;
        assert t != null;
        t.setText((_vok.reverse || showBeds ? _vok.getBedeutung3() : Vokabel.getComment(_vok.getBedeutung3())));
        if (_vok.getFontBed().getName().equalsIgnoreCase("Cardo")) {
            t.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
        }
        if (libString.IsNullOrEmpty(_vok.getBedeutung3()) || _vok.getCardMode()) {
            t.setVisibility(View.GONE);
            _txtMeaning2.setImeOptions(EditorInfo.IME_ACTION_DONE);
        } else {
            t.setVisibility(View.VISIBLE);
            _txtMeaning2.setImeOptions(EditorInfo.IME_ACTION_NEXT);
            _txtMeaning3.setImeOptions(EditorInfo.IME_ACTION_DONE);
            if (_vok.reverse || showBeds) {
                String txt = t.getText().toString();
                //if (txtWord != null)
                //   txt = txt.replaceAll("_{2,}", txtWord).replaceAll("\\.{4,}", txtWord);
                speak(txt, _vok.getLangMeaning(), "meaning3");
            }
        }

        if (_vok.reverse && showBeds)
            speak(txtWord, _vok.getLangWord(), "word");

        lib.setBgEditText(_txtMeaning1, _MeaningBG);
        lib.setBgEditText(_txtMeaning2, _MeaningBG);
        lib.setBgEditText(_txtMeaning3, _MeaningBG);
        if (!_isSmallDevice && !requestFocusEdWord) {
            _txtMeaning1.requestFocus();
        } else {
            if (!requestFocusEdWord)
                _txtWord.requestFocus();
            else
                _txtedWord.requestFocus();
        }
        SetActionBarTitle();

        _scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                lib.removeLayoutListener(_scrollView.getViewTreeObserver(), this);
                hideKeyboard();
                if (showBeds) {
                    _scrollView.scrollTo(0, _txtMeaning1.getTop());
                } else {
                    _txtWord.requestFocus();
                    _scrollView.fullScroll(View.FOCUS_UP);
                }
            }
        });

    } catch (Exception e) {

        lib.ShowException(_main, e);
    }

}

From source file:com.tct.mail.browse.ConversationItemView.java

SpannableStringBuilder elideParticipants(List<SpannableString> parts) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    float totalWidth = 0;
    boolean ellipsize = false;
    float width;//  w ww.  ja  va2 s .c  om
    boolean skipToHeader = false;

    // start with "To: " if we're showing recipients
    if (mDisplayedFolder.shouldShowRecipients() && !parts.isEmpty()) {
        final SpannableString toHeader = SendersView.getFormattedToHeader();
        CharacterStyle[] spans = toHeader.getSpans(0, toHeader.length(), CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        totalWidth += sPaint.measureText(toHeader.toString());
        builder.append(toHeader);
        skipToHeader = true;
    }

    final SpannableStringBuilder messageInfoString = mHeader.messageInfoString;
    if (messageInfoString.length() > 0) {
        CharacterStyle[] spans = messageInfoString.getSpans(0, messageInfoString.length(),
                CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // Paint the message info string to see if we lose space.
        float messageInfoWidth = sPaint.measureText(messageInfoString.toString());
        totalWidth += messageInfoWidth;
    }
    SpannableString prevSender = null;
    SpannableString ellipsizedText;
    for (SpannableString sender : parts) {
        // There may be null sender strings if there were dupes we had to remove.
        if (sender == null) {
            continue;
        }
        // No more width available, we'll only show fixed fragments.
        if (ellipsize) {
            break;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        // There is only 1 character style span.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // If there are already senders present in this string, we need to
        // make sure we prepend the dividing token
        if (SendersView.sElidedString.equals(sender.toString())) {
            prevSender = sender;
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (!skipToHeader && builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            prevSender = sender;
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            prevSender = sender;
            skipToHeader = false;
        }
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_S
        // Measure the width of the current sender and make sure we have space
        width = (int) sPaint.measureText(sender.toString());
        if (width + totalWidth > mCoordinates.sendersWidth) {
            // The text is too long, new line won't help. We have to
            // ellipsize text.
            ellipsize = true;
            width = mCoordinates.sendersWidth - totalWidth; // ellipsis width?
            ellipsizedText = copyStyles(spans, TextUtils.ellipsize(sender, sPaint, width, TruncateAt.END));
            width = (int) sPaint.measureText(ellipsizedText.toString());
        } else {
            ellipsizedText = null;
        }
        totalWidth += width;
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_E

        //[FEATURE]-Add-BEGIN by CDTS.zhonghua.tuo,05/29/2014,FR 670064
        CharSequence fragmentDisplayText;
        if (ellipsizedText != null) {
            fragmentDisplayText = ellipsizedText;
        } else {
            fragmentDisplayText = sender;
        }
        boolean filterSender = false;
        if (mField == UIProvider.LOCAL_SEARCH_ALL || mField == UIProvider.LOCAL_SEARCH_FROM) {
            filterSender = true;
        }
        if (mQueryText != null && filterSender) {
            fragmentDisplayText = TextUtilities.highlightTermsInText(fragmentDisplayText.toString(),
                    mQueryText);
        }
        //[FEATURE]-Add-END by CDTS.zhonghua.tuo
        builder.append(fragmentDisplayText);
    }
    mHeader.styledMessageInfoStringOffset = builder.length();
    builder.append(messageInfoString);
    return builder;
}

From source file:com.android.ex.chips.RecipientEditTextView.java

private CharSequence createChip(final RecipientEntry entry, final boolean pressed) {
    final String displayText = createAddressText(entry);
    if (TextUtils.isEmpty(displayText))
        return null;
    SpannableString chipText = null;
    // Always leave a blank space at the end of a chip.
    final int textLength = displayText.length() - 1;
    chipText = new SpannableString(displayText);
    if (!mNoChips)
        try {//from   w w  w  .  j  a v a2 s. c o  m
            final DrawableRecipientChip chip = constructChipSpan(entry, pressed, false /*
                                                                                        * leave space for contact
                                                                                        * icon
                                                                                        */);
            chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            chip.setOriginalText(chipText.toString());
        } catch (final NullPointerException e) {
            Log.e(TAG, e.getMessage(), e);
            return null;
        }
    return chipText;
}