Example usage for android.text SpannableStringBuilder setSpan

List of usage examples for android.text SpannableStringBuilder setSpan

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder setSpan.

Prototype

public void setSpan(Object what, int start, int end, int flags) 

Source Link

Document

Mark the specified range of text with the specified object.

Usage

From source file:org.kontalk.ui.view.TextContentView.java

private SpannableStringBuilder formatMessage(final Pattern highlight) {
    SpannableStringBuilder buf;

    String textContent = mComponent.getContent();

    buf = new SpannableStringBuilder(textContent);

    if (highlight != null) {
        Matcher m = highlight.matcher(buf.toString());
        while (m.find())
            buf.setSpan(mHighlightColorSpan, m.start(), m.end(), 0);
    }/*from   w  w w .j a  v  a  2 s.  c om*/

    return buf;
}

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

public void setFolders(ConversationViewHeaderCallbacks callbacks, Account account, Conversation conv) {
    mVisibleFolders = true;//ww  w .  j  a  va  2  s.  com
    final BidiFormatter bidiFormatter = getBidiFormatter();
    final String wrappedSubject = mSubject == null ? "" : bidiFormatter.unicodeWrap(mSubject);
    final SpannableStringBuilder sb = new SpannableStringBuilder(wrappedSubject);
    sb.append('\u0020');
    final Settings settings = account.settings;
    final int start = sb.length();
    if (settings.importanceMarkersEnabled && conv.isImportant()) {
        sb.append(".\u0020");
        sb.setSpan(new ReplacementSpan() {
            @Override
            public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
                return mImportanceMarkerDrawable.getIntrinsicWidth();
            }

            @Override
            public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top,
                    int baseline, int bottom, Paint paint) {
                canvas.save();
                final int transY = baseline + mChipVerticalOffset
                        - mImportanceMarkerDrawable.getIntrinsicHeight();
                canvas.translate(x, transY);
                mImportanceMarkerDrawable.draw(canvas);
                canvas.restore();
            }
        }, start, start + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    mFolderDisplayer.loadConversationFolders(conv, null /* ignoreFolder */, -1 /* ignoreFolderType */);
    mFolderDisplayer.constructFolderChips(sb);

    final int end = sb.length();
    sb.setSpan(new ChangeLabelsSpan(callbacks), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    setText(sb);
    setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:us.phyxsi.gameshelf.ui.HomeActivity.java

private void setNoResultsEmptyTextVisibility(int visibility) {
    if (visibility == View.VISIBLE) {
        if (noResultsEmptyText == null) {
            // create the no results empty text
            ViewStub stub = (ViewStub) findViewById(R.id.stub_no_results);
            noResultsEmptyText = (TextView) stub.inflate();
            String emptyText = getString(R.string.no_results_found);
            int addPlaceholderStart = emptyText.indexOf('\u08B4');
            int altMethodStart = addPlaceholderStart + 3;
            SpannableStringBuilder ssb = new SpannableStringBuilder(emptyText);
            // show an image of the add icon
            ssb.setSpan(new ImageSpan(this, R.drawable.ic_add_small, ImageSpan.ALIGN_BASELINE),
                    addPlaceholderStart, addPlaceholderStart + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // make the alt method (swipe from right) less prominent and italic
            ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_secondary_light)),
                    altMethodStart, emptyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new StyleSpan(Typeface.ITALIC), altMethodStart, emptyText.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            noResultsEmptyText.setText(ssb);
        }//  w w  w.j  a v a  2s.  c  o  m

        noResultsEmptyText.setVisibility(visibility);
    } else if (noResultsEmptyText != null) {
        noResultsEmptyText.setVisibility(visibility);
    }
}

From source file:com.collecdoo.fragment.main.RegisterDriverPhotoFragment.java

private void setColorSpan(TextView textView, int fromPos, int toPos) {
    SpannableStringBuilder sb = new SpannableStringBuilder(textView.getText());
    ForegroundColorSpan fcs = new ForegroundColorSpan(Color.RED);
    sb.setSpan(fcs, fromPos, toPos, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(sb);/*from   w w w  . j  a v a  2s . c o m*/
}

From source file:com.chen.mail.browse.SendersView.java

public static SpannableStringBuilder createMessageInfo(Context context, Conversation conv,
        final boolean resourceCachingRequired) {
    SpannableStringBuilder messageInfo = new SpannableStringBuilder();

    try {//w w  w  . java  2 s.c om
        ConversationInfo conversationInfo = conv.conversationInfo;
        int sendingStatus = conv.sendingState;
        boolean hasSenders = false;
        // This covers the case where the sender is "me" and this is a draft
        // message, which means this will only run once most of the time.
        for (MessageInfo m : conversationInfo.messageInfos) {
            if (!TextUtils.isEmpty(m.sender)) {
                hasSenders = true;
                break;
            }
        }
        getSenderResources(context, resourceCachingRequired);
        if (conversationInfo != null) {
            int count = conversationInfo.messageCount;
            int draftCount = conversationInfo.draftCount;
            boolean showSending = sendingStatus == UIProvider.ConversationSendingState.SENDING;
            if (count > 1) {
                messageInfo.append(count + "");
            }
            messageInfo.setSpan(
                    CharacterStyle.wrap(conv.read ? sMessageInfoReadStyleSpan : sMessageInfoUnreadStyleSpan), 0,
                    messageInfo.length(), 0);
            if (draftCount > 0) {
                // If we are showing a message count or any draft text and there
                // is at least 1 sender, prepend the sending state text with a
                // comma.
                if (hasSenders || count > 1) {
                    messageInfo.append(sSendersSplitToken);
                }
                SpannableStringBuilder draftString = new SpannableStringBuilder();
                if (draftCount == 1) {
                    draftString.append(sDraftSingularString);
                } else {
                    draftString.append(sDraftPluralString + String.format(sDraftCountFormatString, draftCount));
                }
                draftString.setSpan(CharacterStyle.wrap(sDraftsStyleSpan), 0, draftString.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageInfo.append(draftString);
            }
            if (showSending) {
                // If we are showing a message count or any draft text, prepend
                // the sending state text with a comma.
                if (count > 1 || draftCount > 0) {
                    messageInfo.append(sSendersSplitToken);
                }
                SpannableStringBuilder sending = new SpannableStringBuilder();
                sending.append(sSendingString);
                sending.setSpan(sSendingStyleSpan, 0, sending.length(), 0);
                messageInfo.append(sending);
            }
            // Prepend a space if we are showing other message info text.
            if (count > 1 || (draftCount > 0 && hasSenders) || showSending) {
                messageInfo.insert(0, sMessageCountSpacerString);
            }
        }
    } finally {
        if (!resourceCachingRequired) {
            clearResourceCache();
        }
    }

    return messageInfo;
}

From source file:com.markupartist.sthlmtraveling.ui.view.TripView.java

public void updateViews() {
    this.setOrientation(VERTICAL);

    float scale = getResources().getDisplayMetrics().density;

    this.setPadding(getResources().getDimensionPixelSize(R.dimen.list_horizontal_padding),
            getResources().getDimensionPixelSize(R.dimen.list_vertical_padding),
            getResources().getDimensionPixelSize(R.dimen.list_horizontal_padding),
            getResources().getDimensionPixelSize(R.dimen.list_vertical_padding));

    LinearLayout timeStartEndLayout = new LinearLayout(getContext());
    TextView timeStartEndText = new TextView(getContext());
    timeStartEndText.setText(DateTimeUtil.routeToTimeDisplay(getContext(), trip));
    timeStartEndText.setTextColor(ContextCompat.getColor(getContext(), R.color.body_text_1));
    timeStartEndText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

    ViewCompat.setPaddingRelative(timeStartEndText, 0, 0, 0, (int) (2 * scale));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        if (RtlUtils.isRtl(Locale.getDefault())) {
            timeStartEndText.setTextDirection(View.TEXT_DIRECTION_RTL);
        }//from  w w w .j  a v a  2 s  . co  m
    }

    // Check if we have Realtime for start and or end.
    boolean hasRealtime = false;
    Pair<Date, RealTimeState> transitTime = trip.departsAt(true);
    if (transitTime.second != RealTimeState.NOT_SET) {
        hasRealtime = true;
    } else {
        transitTime = trip.arrivesAt(true);
        if (transitTime.second != RealTimeState.NOT_SET) {
            hasRealtime = true;
        }
    }
    //        if (hasRealtime) {
    //            ImageView liveDrawable = new ImageView(getContext());
    //            liveDrawable.setImageResource(R.drawable.ic_live);
    //            ViewCompat.setPaddingRelative(liveDrawable, 0, (int) (2 * scale), (int) (4 * scale), 0);
    //            timeStartEndLayout.addView(liveDrawable);
    //
    //            AlphaAnimation animation1 = new AlphaAnimation(0.4f, 1.0f);
    //            animation1.setDuration(600);
    //            animation1.setRepeatMode(Animation.REVERSE);
    //            animation1.setRepeatCount(Animation.INFINITE);
    //
    //            liveDrawable.startAnimation(animation1);
    //        }

    timeStartEndLayout.addView(timeStartEndText);

    LinearLayout startAndEndPointLayout = new LinearLayout(getContext());
    TextView startAndEndPoint = new TextView(getContext());
    BidiFormatter bidiFormatter = BidiFormatter.getInstance(RtlUtils.isRtl(Locale.getDefault()));
    startAndEndPoint.setText(String.format("%s  %s", bidiFormatter.unicodeWrap(trip.fromStop().getName()),
            bidiFormatter.unicodeWrap(trip.toStop().getName())));

    startAndEndPoint.setTextColor(getResources().getColor(R.color.body_text_1)); // Dark gray
    startAndEndPoint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        if (RtlUtils.isRtl(Locale.getDefault())) {
            startAndEndPoint.setTextDirection(View.TEXT_DIRECTION_RTL);
        }
    }
    ViewCompat.setPaddingRelative(startAndEndPoint, 0, (int) (4 * scale), 0, (int) (4 * scale));
    startAndEndPointLayout.addView(startAndEndPoint);

    RelativeLayout timeLayout = new RelativeLayout(getContext());

    LinearLayout routeChanges = new LinearLayout(getContext());
    routeChanges.setGravity(Gravity.CENTER_VERTICAL);

    LinearLayout.LayoutParams changesLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.MATCH_PARENT);
    changesLayoutParams.gravity = Gravity.CENTER_VERTICAL;

    if (trip.hasAlertsOrNotes()) {
        ImageView warning = new ImageView(getContext());
        warning.setImageResource(R.drawable.ic_trip_deviation);
        ViewCompat.setPaddingRelative(warning, 0, (int) (2 * scale), (int) (4 * scale), 0);
        routeChanges.addView(warning);
    }

    int currentTransportCount = 1;
    int transportCount = trip.getLegs().size();
    for (Leg leg : trip.getLegs()) {
        if (!leg.isTransit() && transportCount > 3) {
            if (leg.getDistance() < 150) {
                continue;
            }
        }
        if (currentTransportCount > 1 && transportCount >= currentTransportCount) {
            ImageView separator = new ImageView(getContext());
            separator.setImageResource(R.drawable.transport_separator);
            ViewCompat.setPaddingRelative(separator, 0, 0, (int) (2 * scale), 0);
            separator.setLayoutParams(changesLayoutParams);
            routeChanges.addView(separator);
            if (RtlUtils.isRtl(Locale.getDefault())) {
                ViewCompat.setScaleX(separator, -1f);
            }
        }

        ImageView changeImageView = new ImageView(getContext());
        Drawable transportDrawable = LegUtil.getTransportDrawable(getContext(), leg);
        changeImageView.setImageDrawable(transportDrawable);
        if (RtlUtils.isRtl(Locale.getDefault())) {
            ViewCompat.setScaleX(changeImageView, -1f);
        }
        ViewCompat.setPaddingRelative(changeImageView, 0, 0, 0, 0);
        changeImageView.setLayoutParams(changesLayoutParams);
        routeChanges.addView(changeImageView);

        if (currentTransportCount <= 3) {
            String lineName = leg.getRouteShortName();
            if (!TextUtils.isEmpty(lineName)) {
                TextView lineNumberView = new TextView(getContext());
                lineNumberView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                RoundedBackgroundSpan roundedBackgroundSpan = new RoundedBackgroundSpan(
                        LegUtil.getColor(getContext(), leg), Color.WHITE,
                        ViewHelper.dipsToPix(getContext().getResources(), 4));
                SpannableStringBuilder sb = new SpannableStringBuilder();
                sb.append(lineName);
                sb.append(' ');
                sb.setSpan(roundedBackgroundSpan, 0, lineName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                lineNumberView.setText(sb);

                ViewCompat.setPaddingRelative(lineNumberView, (int) (5 * scale), (int) (1 * scale),
                        (int) (2 * scale), 0);
                lineNumberView.setLayoutParams(changesLayoutParams);
                routeChanges.addView(lineNumberView);
            }
        }

        currentTransportCount++;
    }

    TextView durationText = new TextView(getContext());
    durationText.setText(DateTimeUtil.formatDetailedDuration(getResources(), trip.getDuration() * 1000));
    durationText.setTextColor(ContextCompat.getColor(getContext(), R.color.body_text_1));
    durationText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    durationText.setTypeface(Typeface.DEFAULT_BOLD);

    timeLayout.addView(routeChanges);
    timeLayout.addView(durationText);

    RelativeLayout.LayoutParams durationTextParams = (RelativeLayout.LayoutParams) durationText
            .getLayoutParams();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        durationTextParams.addRule(RelativeLayout.ALIGN_PARENT_END);
    } else {
        durationTextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    }
    durationText.setLayoutParams(durationTextParams);

    View divider = new View(getContext());
    ViewGroup.LayoutParams dividerParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
    divider.setLayoutParams(dividerParams);

    this.addView(timeLayout);

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) routeChanges.getLayoutParams();
    params.height = LayoutParams.MATCH_PARENT;
    params.addRule(RelativeLayout.CENTER_VERTICAL);
    routeChanges.setLayoutParams(params);

    this.addView(startAndEndPointLayout);
    this.addView(timeStartEndLayout);

    if (mShowDivider) {
        this.addView(divider);
    }
}

From source file:org.telegram.ui.Cells.BotHelpCell.java

public void setText(String text) {
    if (text == null || text.length() == 0) {
        setVisibility(GONE);/*from  ww w.ja  va 2s  .  c o  m*/
        return;
    }
    if (text != null && oldText != null && text.equals(oldText)) {
        return;
    }
    oldText = text;
    setVisibility(VISIBLE);
    if (AndroidUtilities.isTablet()) {
        width = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
    } else {
        width = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
    }
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
    String help = LocaleController.getString("BotInfoTitle", R.string.BotInfoTitle);
    stringBuilder.append(help);
    stringBuilder.append("\n\n");
    stringBuilder.append(text);
    MessageObject.addLinks(stringBuilder);
    stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, help.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    Emoji.replaceEmoji(stringBuilder, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
    try {
        textLayout = new StaticLayout(stringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f,
                0.0f, false);
        width = 0;
        height = textLayout.getHeight() + AndroidUtilities.dp(4 + 18);
        int count = textLayout.getLineCount();
        for (int a = 0; a < count; a++) {
            width = (int) Math.ceil(Math.max(width, textLayout.getLineWidth(a) + textLayout.getLineLeft(a)));
        }
    } catch (Exception e) {
        FileLog.e("tmessage", e);
    }
    width += AndroidUtilities.dp(4 + 18);
}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

public static SpannableStringBuilder createSpan(Context context, String text, ImageSpanTag[] tags) {
    SpannableStringBuilder span = new SpannableStringBuilder(text);
    ImageSpan blank = createImageSpan(context, R.drawable.ic_transparent, 0, 0, R.color.transparent);

    for (ImageSpanTag tag : tags) {
        String spanTag = tag.getTag();
        ImageSpan imageSpan = (tag.getSpan() == null) ? blank : tag.getSpan();

        int tagPos;
        while ((tagPos = text.indexOf(spanTag)) >= 0) {
            int tagEnd = tagPos + spanTag.length();
            //Log.d("DEBUG", "tag=" + spanTag + ", tagPos=" + tagPos + ", " + tagEnd + ", text=" + text);

            span.setSpan(createImageSpan(imageSpan), tagPos, tagEnd, ImageSpan.ALIGN_BASELINE);
            text = text.substring(0, tagPos) + tag.getBlank() + text.substring(tagEnd);
        }/* w w  w  .  ja v a  2  s . c  o  m*/
    }
    return span;
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

private static void startImg(SpannableStringBuilder text, Attributes attributes, HtmlParser.ImageGetter img) {
    String src = attributes.getValue("", "src");
    Drawable d = null;//w  w  w  .  j  a v  a  2 s  . co  m

    if (img != null) {
        d = img.getDrawable(src);
    }

    if (d == null) {
        d = ResourcesCompat.getDrawable(Resources.getSystem(), android.R.drawable.ic_menu_report_image, null);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    }

    int len = text.length();
    text.append("\uFFFC");

    text.setSpan(new ImageSpan(d, src), len, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

private static void startSpan(SpannableStringBuilder text, Attributes attributes) {
    String style = attributes.getValue("", "style");
    String classAttr = attributes.getValue("", "class");
    boolean isAibquote = classAttr != null && (classAttr.equals("unkfunc") || classAttr.equals("quote"));
    boolean isAibspoiler = classAttr != null && classAttr.equals("spoiler");
    boolean isUnderline = classAttr != null && classAttr.equals("u");
    boolean isStrike = classAttr != null && classAttr.equals("s");

    int len = text.length();
    text.setSpan(new Span(style, isAibquote, isAibspoiler, isUnderline, isStrike), len, len,
            Spannable.SPAN_MARK_MARK);//from  www.  j  ava  2s.c o  m
}