Example usage for android.text SpannableStringBuilder replace

List of usage examples for android.text SpannableStringBuilder replace

Introduction

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

Prototype

public SpannableStringBuilder replace(int start, int end, CharSequence tb) 

Source Link

Usage

From source file:Main.java

public static void makeAboutSpannable(SpannableStringBuilder span, String str_link, String replace,
        final Runnable on_click) {
    Pattern pattern = Pattern.compile(str_link);
    Matcher matcher = pattern.matcher(span);
    ForegroundColorSpan color_theme = new ForegroundColorSpan(Color.parseColor("#53b7bb"));
    if (matcher.find()) {
        span.setSpan(new ClickableSpan() {
            @Override/*from   w  w  w  .j  a  v  a  2  s  .c  o m*/
            public void onClick(View widget) {
                if (on_click != null)
                    on_click.run();
            }
        }, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(color_theme, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (replace != null)
            span.replace(matcher.start(), matcher.end(), replace);
    }
}

From source file:org.pencilsofpromise.rss.RSSFragment.java

private Spanned removeContentSpanObjects(String sb) {
    SpannableStringBuilder spannedStr = (SpannableStringBuilder) Html.fromHtml(sb.toString().trim());
    Object[] spannedObjects = spannedStr.getSpans(0, spannedStr.length(), Object.class);
    for (int i = 0; i < spannedObjects.length; i++) {

        if (spannedObjects[i] instanceof ImageSpan)
            spannedStr.replace(spannedStr.getSpanStart(spannedObjects[i]),
                    spannedStr.getSpanEnd(spannedObjects[i]), "");

    }/*from  ww  w. j a v a2s.c o m*/
    return spannedStr;
}

From source file:com.owncloud.android.ui.adapter.NotificationListAdapter.java

private SpannableStringBuilder makeSpecialPartsBold(Notification notification) {
    String text = notification.getSubjectRich();
    SpannableStringBuilder ssb = new SpannableStringBuilder(text);

    int openingBrace = text.indexOf('{');
    int closingBrace;
    String replaceablePart;/* w ww  .j a  v  a2  s  . com*/
    while (openingBrace != -1) {
        closingBrace = text.indexOf('}', openingBrace) + 1;
        replaceablePart = text.substring(openingBrace + 1, closingBrace - 1);

        RichObject richObject = notification.subjectRichParameters.get(replaceablePart);
        if (richObject != null) {
            String name = richObject.getName();
            ssb.replace(openingBrace, closingBrace, name);
            text = ssb.toString();
            closingBrace = openingBrace + name.length();

            ssb.setSpan(styleSpanBold, openingBrace, closingBrace, 0);
            ssb.setSpan(foregroundColorSpanBlack, openingBrace, closingBrace,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        openingBrace = text.indexOf('{', closingBrace);
    }

    return ssb;
}

From source file:com.ruesga.rview.tasks.AsyncTextDiffProcessor.java

private CharSequence processHighlightTabs(CharSequence text) {
    if (!mHighlightTabs || !text.toString().contains(StringHelper.NON_PRINTABLE_CHAR)) {
        return text;
    }//  w  w w  .ja  v  a  2s . c o m

    int color = ContextCompat.getColor(mContext, R.color.diffHighlightColor);
    SpannableStringBuilder ssb = new SpannableStringBuilder(text);
    String line = text.toString();
    int index = line.length();
    while ((index = line.lastIndexOf(StringHelper.NON_PRINTABLE_CHAR, index)) != -1) {
        ssb.replace(index, index + 1, "\u00BB    ");
        ssb.setSpan(new ForegroundColorSpan(color), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(Typeface.BOLD), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        index--;
    }
    return ssb;
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Return a new CharSequence in which each of the source strings is
 * replaced by the corresponding element of the destinations.
 *///from  ww w.j a v a2s .  co  m
public static CharSequence replace(CharSequence template, String[] sources, CharSequence[] destinations) {
    SpannableStringBuilder tb = new SpannableStringBuilder(template);

    for (int i = 0; i < sources.length; i++) {
        int where = indexOf(tb, sources[i]);

        if (where >= 0)
            tb.setSpan(sources[i], where, where + sources[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    for (int i = 0; i < sources.length; i++) {
        int start = tb.getSpanStart(sources[i]);
        int end = tb.getSpanEnd(sources[i]);

        if (start >= 0) {
            tb.replace(start, end, destinations[i]);
        }
    }

    return tb;
}

From source file:com.ruesga.rview.misc.Formatter.java

@BindingAdapter("userMessage")
public static void toUserMessage(TextView view, String msg) {
    if (msg == null) {
        view.setText(null);//from  w w  w .  ja  va2s .c  om
        return;
    }

    String message = EmojiHelper.createEmoji(msg);

    // This process mimics the Gerrit formatting process done in class
    // ./gerrit-gwtexpui/src/main/java/com/google/gwtexpui/safehtml/client/SafeHtml.java

    // Split message into paragraphs
    String[] paragraphs = StringHelper.obtainParagraphs(message);
    StringBuilder sb = new StringBuilder();
    boolean formattedMessage = false;
    for (String p : paragraphs) {
        if (StringHelper.isQuote(p)) {
            sb.append(StringHelper.obtainQuote(StringHelper.removeLineBreaks(p)));
            formattedMessage = true;
        } else if (StringHelper.isList(p)) {
            sb.append(p);
            formattedMessage = true;
        } else if (StringHelper.isPreFormat(p)) {
            sb.append(StringHelper.obtainPreFormatMessage(p));
            formattedMessage = true;
        } else {
            sb.append(p);
        }
        sb.append("\n\n");
    }

    String userMessage = StringHelper.removeExtraLines(sb.toString());
    if (!formattedMessage) {
        view.setText(userMessage);
        return;
    }

    if (sQuoteColor == -1) {
        sQuoteColor = ContextCompat.getColor(view.getContext(), R.color.quote);
        sQuoteWidth = (int) view.getContext().getResources().getDimension(R.dimen.quote_width);
        sQuoteMargin = (int) view.getContext().getResources().getDimension(R.dimen.quote_margin);
    }

    String[] lines = userMessage.split("\n");
    SpannableStringBuilder spannable = new SpannableStringBuilder(userMessage
            .replaceAll(StringHelper.NON_PRINTABLE_CHAR, "").replaceAll(StringHelper.NON_PRINTABLE_CHAR2, ""));

    // Pre-Format
    int start = 0;
    int spans = 0;
    while ((start = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start)) != -1) {
        int end = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start + 1);
        if (end == -1) {
            //? This is supposed to be formatted by us. Skip it
            break;
        }

        // Find quote token occurrences
        int offset = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, userMessage, 0, start);
        start -= offset;
        end -= offset;

        // Ensure bounds
        int spanStart = start - spans;
        int spanEnd = Math.min(end - spans - 1, spannable.length());
        if (spanStart < 0 || spanEnd < 0) {
            //Something was wrong. Skip it
            break;
        }
        spannable.setSpan(new RelativeSizeSpan(0.8f), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new TypefaceSpan("monospace"), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        start = end;
        spans++;
    }

    start = 0;
    for (String line : lines) {
        // Quotes
        int maxIndent = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, line);
        for (int i = 0; i < maxIndent; i++) {
            QuotedSpan span = new QuotedSpan(sQuoteColor, sQuoteWidth, sQuoteMargin);
            spannable.setSpan(span, start, Math.min(start + line.length() - maxIndent, spannable.length()),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        // List
        if (StringHelper.isList(line)) {
            spannable.replace(start, start + 1, "\u2022");
            spannable.setSpan(new LeadingMarginSpan.Standard(sQuoteMargin), start,
                    Math.min(start + line.length(), spannable.length()), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        start += line.length() - maxIndent + 1;
    }

    view.setText(spannable);
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Replace instances of "^1", "^2", etc. in the
 * <code>template</code> CharSequence with the corresponding
 * <code>values</code>.  "^^" is used to produce a single caret in
 * the output.  Only up to 9 replacement values are supported,
 * "^10" will be produce the first replacement value followed by a
 * '0'./*from w w w . ja v  a 2 s  .c o  m*/
 *
 * @param template the input text containing "^1"-style
 * placeholder values.  This object is not modified; a copy is
 * returned.
 *
 * @param values CharSequences substituted into the template.  The
 * first is substituted for "^1", the second for "^2", and so on.
 *
 * @return the new CharSequence produced by doing the replacement
 *
 * @throws IllegalArgumentException if the template requests a
 * value that was not provided, or if more than 9 values are
 * provided.
 */
public static CharSequence expandTemplate(CharSequence template, CharSequence... values) {
    if (values.length > 9) {
        throw new IllegalArgumentException("max of 9 values are supported");
    }

    SpannableStringBuilder ssb = new SpannableStringBuilder(template);

    try {
        int i = 0;
        while (i < ssb.length()) {
            if (ssb.charAt(i) == '^') {
                char next = ssb.charAt(i + 1);
                if (next == '^') {
                    ssb.delete(i + 1, i + 2);
                    ++i;
                    continue;
                } else if (Character.isDigit(next)) {
                    int which = Character.getNumericValue(next) - 1;
                    if (which < 0) {
                        throw new IllegalArgumentException("template requests value ^" + (which + 1));
                    }
                    if (which >= values.length) {
                        throw new IllegalArgumentException("template requests value ^" + (which + 1) + "; only "
                                + values.length + " provided");
                    }
                    ssb.replace(i, i + 2, values[which]);
                    i += values[which].length();
                    continue;
                }
            }
            ++i;
        }
    } catch (IndexOutOfBoundsException ignore) {
        // happens when ^ is the last character in the string.
    }
    return ssb;
}

From source file:com.amazon.android.ui.widget.EllipsizedTextView.java

/**
 * Sets ellipsis properties.// w  w  w  . j av  a  2s. co m
 *
 * @param widthMeasureSpec  Ellipsis width.
 * @param heightMeasureSpec Ellipsis height.
 * @param layout            Layout for ellipsis.
 * @param lastLine          Last line length for ellipsis.
 * @param maxLines          Max lines in ellipsis.
 */
private void setEllipsis(int widthMeasureSpec, int heightMeasureSpec, Layout layout, int lastLine,
        int maxLines) {

    mIsEllipsized = true;
    setFocusable(true);
    setClickable(true);
    final SpannableString ss = new SpannableString(mCharSequence);
    String visibleText = mCharSequence.toString();

    mEllipsisImage = new StateImageSpan(getContext(), mGuillemetDrawableId, ImageSpan.ALIGN_BASELINE);

    final SpannableStringBuilder spannedText = new SpannableStringBuilder();
    int ellipsisIndex = layout.getLineStart(Math.min(lastLine + 1, maxLines));

    // Keep chopping words off until the ellipsis is on a visible line or there is only one
    // line left.
    do {
        // Only truncate the last line for long description.
        if (lastLine >= maxLines) {
            // Getting the first word break index before the last index of maxline.
            int safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getWordInstance());
            final int maxLineStart = layout.getLineStart(maxLines - 1);

            // If this check pass, it means we just truncated a word that is longer than a line.
            if (safeBreakIndex < maxLineStart) {
                // Need to check character by character and break in the middle now. Checking
                // word by word should cover most cases, only do this if a word is longer than
                // line width.
                safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getCharacterInstance());
            }
            ellipsisIndex = safeBreakIndex;
        }

        visibleText = visibleText.substring(0, ellipsisIndex);
        final CharSequence charOutput = ss.subSequence(0, ellipsisIndex);

        // Re-add ellipsis and convert to image
        spannedText.replace(0, spannedText.length(), charOutput);
        spannedText.append(ELLIPSIS);

        spannedText.setSpan(mEllipsisImage, ellipsisIndex, ellipsisIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

        // Reset text and re-measure.
        super.setText(spannedText, BufferType.SPANNABLE);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    } while (getLineCount() > getMaxLines() && getLineCount() > 1);
    requestFocus();
}

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

private void createSnippet() {
    final String snippet = mHeader.conversation.getSnippet();
    /// TCT: add for search term highlight
    // process subject and snippet respectively @{
    SpannableStringBuilder snippetToHighlight = new SpannableStringBuilder(snippet);
    boolean hasFilter = (mSearchParams != null && !TextUtils.isEmpty(mSearchParams.mFilter));
    if (hasFilter) {
        boolean fieldMatchedSnippet = (mSearchParams != null
                && (SearchParams.SEARCH_FIELD_BODY.equals(mSearchParams.mField)
                        || SearchParams.SEARCH_FIELD_ALL.equals(mSearchParams.mField)));

        /// TCT: Only highlight un-empty snippet
        if (fieldMatchedSnippet && !TextUtils.isEmpty(snippet)) {
            CharSequence snippetChars = TextUtilities.highlightTermsInText(snippet, mSearchParams.mFilter);
            snippetToHighlight.replace(0, snippet.length(), snippetChars);
        }/*from  www . jav  a  2  s. com*/
    }
    /// @}
    final Spannable displayedStringBuilder = new SpannableString(snippetToHighlight);

    // measure the width of the folders which overlap the snippet view
    final int folderWidth = mHeader.folderDisplayer.measureFolders(mCoordinates);

    // size the snippet view by subtracting the folder width from the maximum snippet width
    final int snippetWidth = mCoordinates.maxSnippetWidth - folderWidth;
    final int snippetHeight = mCoordinates.snippetHeight;
    mSnippetTextView.setLayoutParams(new ViewGroup.LayoutParams(snippetWidth, snippetHeight));
    mSnippetTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.snippetFontSize);
    layoutViewExactly(mSnippetTextView, snippetWidth, snippetHeight);

    mSnippetTextView.setText(displayedStringBuilder);
}

From source file:org.telegram.ui.Components.ChatActivityEnterView.java

public void replaceWithText(int start, int len, CharSequence text) {
    try {//ww w  . j a va2 s  .co  m
        SpannableStringBuilder builder = new SpannableStringBuilder(messageEditText.getText());
        builder.replace(start, start + len, text);
        messageEditText.setText(builder);
        messageEditText.setSelection(start + text.length());
    } catch (Exception e) {
        FileLog.e(e);
    }
}