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:Main.java

private static Typeface getTextTypeface(final CharSequence text) {
    if (!(text instanceof SpannableString)) {
        return Typeface.DEFAULT;
    }/*from w w  w . j  a v  a2 s .  com*/

    final SpannableString ss = (SpannableString) text;
    final StyleSpan[] styles = ss.getSpans(0, text.length(), StyleSpan.class);
    if (styles.length == 0) {
        return Typeface.DEFAULT;
    }

    if (styles[0].getStyle() == Typeface.BOLD) {
        return Typeface.DEFAULT_BOLD;
    }
    // TODO: BOLD_ITALIC, ITALIC case?
    return Typeface.DEFAULT;
}

From source file:com.android.talkback.menurules.RuleSpannables.java

/**
 * Retrieves SpannableString in the accessibility node. The content description and text of the
 * node is checked in order./*from   www .  ja va2s .  c o m*/
 * @param node
 * @return SpannableString with at least 1 UrlSpan. null if no UrlSpan found in the node.
 */
private static SpannableString getStringWithUrlSpan(AccessibilityNodeInfoCompat node) {
    CharSequence text = node.getContentDescription();
    if (!TextUtils.isEmpty(text)) {
        if (!(text instanceof SpannableString)) {
            return null;
        }
    } else {
        text = node.getText();
        if (TextUtils.isEmpty(text) || !(text instanceof SpannableString)) {
            return null;
        }
    }

    SpannableString spannable = (SpannableString) text;
    final URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
    if (urlSpans == null || urlSpans.length == 0) {
        return null;
    }

    return spannable;
}

From source file:com.vuze.android.remote.AndroidUtilsUI.java

public static void linkify(TextView tv) {
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    CharSequence t = tv.getText();
    if (!(t instanceof SpannableString)) {
        return;/*  www  .  j  a  v  a2  s .c  o  m*/
    }
    SpannableString text = (SpannableString) t;

    int len = text.length();

    int next;
    for (int i = 0; i < text.length(); i = next) {
        next = text.nextSpanTransition(i, len, URLSpan.class);
        URLSpan[] old = text.getSpans(i, next, URLSpan.class);
        for (int j = old.length - 1; j >= 0; j--) {
            text.removeSpan(old[j]);

            UrlSpan2 span2 = new UrlSpan2(old[j].getURL());
            text.setSpan(span2, i, next, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

}

From source file:org.mariotaku.twidere.util.StatusActionModeCallback.java

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    final int start = textView.getSelectionStart(), end = textView.getSelectionEnd();
    final SpannableString string = SpannableString.valueOf(textView.getText());
    final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
    final boolean avail = spans.length == 1 && URLUtil.isValidUrl(spans[0].getURL());
    MenuUtils.setMenuItemAvailability(menu, android.R.id.copyUrl, avail);
    MenuUtils.setMenuItemShowAsActionFlags(menu, android.R.id.copyUrl, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    return true;/*from   www. ja  v a  2s .  c  om*/
}

From source file:org.mariotaku.twidere.util.StatusActionModeCallback.java

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.copyUrl: {
        final int start = textView.getSelectionStart(), end = textView.getSelectionEnd();
        final SpannableString string = SpannableString.valueOf(textView.getText());
        final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
        if (spans.length != 1)
            return true;
        ClipboardUtils.setText(context, spans[0].getURL());
        mode.finish();/*w  w w . java2s . co  m*/
        return true;
    }
    }
    return false;
}

From source file:com.android.screenspeak.menurules.RuleSpannables.java

@Override
public boolean accept(Context context, AccessibilityNodeInfoCompat node) {
    final CharSequence text = node.getText();
    if (!TextUtils.isEmpty(text) && (text instanceof SpannableString)) {
        final SpannableString spannable = (SpannableString) node.getText();
        final URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        if (urlSpans.length > 0) {
            return true;
        }/* www.  j  av a  2  s.c o  m*/
    }

    return false;
}

From source file:com.android.screenspeak.menurules.RuleSpannables.java

@Override
public List<ContextMenuItem> getMenuItemsForNode(ScreenSpeakService service,
        ContextMenuItemBuilder menuItemBuilder, AccessibilityNodeInfoCompat node) {
    final SpannableString spannable = (SpannableString) node.getText();
    final URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
    final LinkedList<ContextMenuItem> result = new LinkedList<>();

    if ((urlSpans == null) || (urlSpans.length == 0)) {
        return result;
    }//from www  .  j  a  va2 s.  co m

    for (int i = 0; i < urlSpans.length; i++) {
        final URLSpan urlSpan = urlSpans[i];
        final String url = urlSpan.getURL();
        final int start = spannable.getSpanStart(urlSpan);
        final int end = spannable.getSpanEnd(urlSpan);
        final CharSequence label = spannable.subSequence(start, end);
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(label)) {
            continue;
        }

        final Uri uri = Uri.parse(url);
        if (uri.isRelative()) {
            // Generally, only absolute URIs are resolvable to an activity
            continue;
        }

        final ContextMenuItem item = menuItemBuilder.createMenuItem(service, Menu.NONE, i, Menu.NONE, label);
        item.setOnMenuItemClickListener(new SpannableMenuClickListener(service, uri));
        result.add(item);
    }

    return result;
}

From source file:com.android.talkback.menurules.RuleSpannables.java

@Override
public List<ContextMenuItem> getMenuItemsForNode(TalkBackService service,
        ContextMenuItemBuilder menuItemBuilder, AccessibilityNodeInfoCompat node) {
    final LinkedList<ContextMenuItem> result = new LinkedList<>();

    final SpannableString spannable = getStringWithUrlSpan(node);
    if (spannable == null) {
        return result;
    }//  w  ww  .j a  v a 2 s . co  m

    final URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
    if ((urlSpans == null) || (urlSpans.length == 0)) {
        return result;
    }

    for (int i = 0; i < urlSpans.length; i++) {
        final URLSpan urlSpan = urlSpans[i];
        final String url = urlSpan.getURL();
        final int start = spannable.getSpanStart(urlSpan);
        final int end = spannable.getSpanEnd(urlSpan);
        final CharSequence label = spannable.subSequence(start, end);
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(label)) {
            continue;
        }

        final Uri uri = Uri.parse(url);
        if (uri.isRelative()) {
            // Generally, only absolute URIs are resolvable to an activity
            continue;
        }

        final ContextMenuItem item = menuItemBuilder.createMenuItem(service, Menu.NONE, i, Menu.NONE, label);
        item.setOnMenuItemClickListener(new SpannableMenuClickListener(service, uri));
        result.add(item);
    }

    return result;
}

From source file:cn.dreamtobe.emoji.ellipsize.helper.SpanEllipsizeEndHelper.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static CharSequence matchMaxWidth(SpannableString targetText, TextView textView) {
    if (targetText.length() <= 0) {
        return targetText;
    }//from   ww  w .  j a v a2  s  .c  om

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        return targetText;
    }

    if (textView == null) {
        return targetText;
    }

    final int maxWidth = textView.getMaxWidth();

    if (maxWidth <= 0 || maxWidth >= Integer.MAX_VALUE) {
        return targetText;
    }

    if (textView.getEllipsize() != TextUtils.TruncateAt.END) {
        return targetText;
    }

    //TODO Multi-lines support
    if (textView.getMaxLines() != 1) {
        return targetText;
    }

    final String maxWidthKey = getMaxWidthKey(targetText, textView);
    SpannableString tmpText = SPAN_MAXWIDTH_CACHE.get(maxWidthKey);
    if (tmpText != null) {
        removeClickableSpan(tmpText);
        return tmpText;
    }

    TextPaint textPaint = textView.getPaint();
    if (textPaint == null) {
        return targetText;
    }

    final int totalWidth = (int) textPaint.measureText(targetText, 0, targetText.length());
    if (totalWidth <= maxWidth) {
        return targetText;
    }

    final long startTime = System.currentTimeMillis();
    // deal maxwitdh

    final int dotWidth = (int) textPaint.measureText("...");

    tmpText = targetText;

    int start = 0;
    int end = targetText.length();

    // targetX is maxWidth - "...".length
    int targetX = maxWidth - dotWidth;

    //dichotomy: get x most touch targetX
    int middle = targetText.length();
    int x = 0;
    while (start <= end) {
        // tx = targetX, tl = targetLength

        // width:  0           x
        // length: 0         middle           end
        //         -------------|-------------
        middle = (start + end) / 2;

        int emojiDraW = 0;
        int emojiStrW = 0;

        int emojiExcursion = 1;

        final Object[] tmpSpans = tmpText.getSpans(0, middle, Object.class);
        if (tmpSpans != null) {
            for (Object tmpSpan : tmpSpans) {
                final int tmpStart = tmpText.getSpanStart(tmpSpan);
                final int tmpEnd = tmpText.getSpanEnd(tmpSpan);

                //middle in (tmpStart, tmpEnd)
                if (tmpStart < middle && tmpEnd > middle) {
                    middle = tmpEnd;
                    emojiExcursion = tmpEnd - tmpStart;
                }
            }

            // TextPaint#measure do not attention span, so adjust by ourselves
            for (Object tmpSpan : tmpSpans) {
                final int tmpStart = tmpText.getSpanStart(tmpSpan);
                final int tmpEnd = tmpText.getSpanEnd(tmpSpan);

                // TODO support other span
                if (tmpStart < middle && tmpSpan instanceof ImageSpan) {
                    emojiDraW += ((ImageSpan) tmpSpan).getDrawable().getBounds().width();
                    emojiStrW += textPaint.measureText(tmpText, tmpStart, tmpEnd);
                }
            }

        }

        x = (int) textPaint.measureText(tmpText, 0, middle);
        x = x - emojiStrW + emojiDraW;

        //            x = (int) (textPaint.measureText(pureStr, 0, pureStr.length()) + emojiWidth);

        //            Log.d(TAG, String.format("targetX: %d, currentX: %d, currentLength: %d, totalLength: %d, emojiStrW[%d], emojiDraW[%d]", targetX, x, middle, targetText.length(), emojiStrW, emojiDraW));

        if (x > targetX) {
            // width:  0       tx        x
            // length: start   tl      middle         end
            //             ----|---------|-------------
            // TO:     start   |       *end
            //             ----|--------|--------------
            end = middle - emojiExcursion;
        } else if (x < targetX) {
            // width:  0               x       tx
            // length: start         middle    tl     end
            //           --------------|-------|------
            // TO:                      *start  |       end
            //           ---------------|------|------
            start = middle + 1;
        } else {
            break;
        }
    }

    // adjust x larger targetX
    while (x > targetX && middle > 0) {
        x = (int) textPaint.measureText(tmpText, 0, --middle);
    }

    // adjust x middle emoji span
    final Object[] ajustSpans = tmpText.getSpans(0, tmpText.length(), Object.class);
    for (Object adjustSpan : ajustSpans) {
        final int adjustStart = tmpText.getSpanStart(adjustSpan);
        final int adjustEnd = tmpText.getSpanEnd(adjustSpan);

        //[adjustStart, adjustEnd)
        if (middle >= adjustStart && middle < adjustEnd) {
            middle = adjustStart - 1;
            break;
        }
    }

    // finnal middle

    // sub sequence [0, middle + 1) & remove [middle +1, length] spans
    tmpText = (SpannableString) tmpText.subSequence(0, middle + 1);
    //        Log.d(TAG, String.format("sub Sequence[0, %d), [%s] to [%s]", middle + 1, targetText, tmpText));

    // add ...
    final SpannableString maxWidthSS = new SpannableString(tmpText + "...");

    final Object[] maxWidthSpans = tmpText.getSpans(0, tmpText.length(), Object.class);
    if (maxWidthSpans != null) {
        for (Object maxWidthSpan : maxWidthSpans) {
            final int mwSpanStart = tmpText.getSpanStart(maxWidthSpan);
            final int mwSpanEnd = tmpText.getSpanEnd(maxWidthSpan);
            final int mwSpanFlag = tmpText.getSpanFlags(maxWidth);

            maxWidthSS.setSpan(maxWidthSpan, mwSpanStart, mwSpanEnd, mwSpanFlag);
        }
    }

    targetText = maxWidthSS;

    SPAN_MAXWIDTH_CACHE.put(maxWidthKey, targetText);
    Log.d(TAG, String.format("deal maxWidth %d", System.currentTimeMillis() - startTime));

    return targetText;
}

From source file:org.thoughtcrime.securesms.ConversationItem.java

private SpannableString linkifyMessageBody(SpannableString messageBody, boolean shouldLinkifyAllLinks) {
    boolean hasLinks = Linkify.addLinks(messageBody, shouldLinkifyAllLinks ? Linkify.ALL : 0);

    if (hasLinks) {
        URLSpan[] urlSpans = messageBody.getSpans(0, messageBody.length(), URLSpan.class);
        for (URLSpan urlSpan : urlSpans) {
            int start = messageBody.getSpanStart(urlSpan);
            int end = messageBody.getSpanEnd(urlSpan);
            messageBody.setSpan(new LongClickCopySpan(urlSpan.getURL()), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }/*w  ww  .  j  av  a 2 s .  c  o m*/
    }
    return messageBody;
}