Example usage for android.text SpannableString getSpans

List of usage examples for android.text SpannableString getSpans

Introduction

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

Prototype

public <T> T[] getSpans(int start, int end, Class<T> type);

Source Link

Document

Return an array of the markup objects attached to the specified slice of this CharSequence and whose type is the specified type or a subclass of it.

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);
    }//  w  w  w. j a  v  a  2s.c  o m

    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:de.vanita5.twittnuker.fragment.support.StatusFragment.java

@Override
public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
    final int start = mTextView.getSelectionStart(), end = mTextView.getSelectionEnd();
    final SpannableString string = SpannableString.valueOf(mTextView.getText());
    final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
    final boolean avail = spans != null && spans.length == 1 && URLUtil.isValidUrl(spans[0].getURL());
    Utils.setMenuItemAvailability(menu, android.R.id.copyUrl, avail);
    return false;
}

From source file:de.vanita5.twittnuker.fragment.support.StatusFragment.java

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.copyUrl: {
        final int start = mTextView.getSelectionStart(), end = mTextView.getSelectionEnd();
        final SpannableString string = SpannableString.valueOf(mTextView.getText());
        final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
        if (spans == null || spans.length != 1)
            return true;
        ClipboardUtils.setText(getActivity(), spans[0].getURL());
        mode.finish();/*  w w w. ja  v a 2s . c  o  m*/
        return true;
    }
    }
    return false;
}

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;/* ww w. j  a v  a 2s.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 (!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: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. co 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 w w  .j  av  a2s. 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.mail.compose.ComposeActivity.java

private static void removeSpansOfType(SpannableString str, Class<?> cls) {
    for (Object span : str.getSpans(0, str.length(), cls)) {
        str.removeSpan(span);/*from ww w .java 2s  .c om*/
    }
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private final void addCallAndContactMenuItems(ContextMenu menu, MsgListMenuClickListener l,
        MessageItem msgItem) {// www  .  j  a v  a2  s.  co  m
    if (TextUtils.isEmpty(msgItem.mBody)) {
        return;
    }
    SpannableString msg = new SpannableString(msgItem.mBody);
    Linkify.addLinks(msg, Linkify.ALL);
    ArrayList<String> uris = MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class));

    // Remove any dupes so they don't get added to the menu multiple times
    HashSet<String> collapsedUris = new HashSet<String>();
    for (String uri : uris) {
        collapsedUris.add(uri.toLowerCase());
    }
    for (String uriString : collapsedUris) {
        String prefix = null;
        int sep = uriString.indexOf(":");
        if (sep >= 0) {
            prefix = uriString.substring(0, sep);
            uriString = uriString.substring(sep + 1);
        }
        Uri contactUri = null;
        boolean knownPrefix = true;
        if ("mailto".equalsIgnoreCase(prefix)) {
            contactUri = getContactUriForEmail(uriString);
        } else if ("tel".equalsIgnoreCase(prefix)) {
            contactUri = getContactUriForPhoneNumber(uriString);
        } else {
            knownPrefix = false;
        }
        if (knownPrefix && contactUri == null) {
            Intent intent = ConversationList.createAddContactIntent(uriString);

            String addContactString = getString(R.string.menu_add_address_to_contacts, uriString);
            menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString).setOnMenuItemClickListener(l)
                    .setIntent(intent);
        }
    }
}