android.text.style.CharacterStyle Java Examples

The following examples show how to use android.text.style.CharacterStyle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InputTestsBase.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
public SpanGetter(final CharSequence inputText,
        final Class<? extends CharacterStyle> spanType) {
    mInputText = (SpannableStringBuilder)inputText;
    final CharacterStyle[] spans =
            mInputText.getSpans(0, mInputText.length(), spanType);
    if (0 == spans.length) {
        mSpan = null;
        mStart = -1;
        mEnd = -1;
    } else if (1 == spans.length) {
        mSpan = spans[0];
        mStart = mInputText.getSpanStart(mSpan);
        mEnd = mInputText.getSpanEnd(mSpan);
    } else {
        throw new RuntimeException("Expected one span, found " + spans.length);
    }
}
 
Example #2
Source File: SpannableSerializer.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static JSONArray extractClass(final SpannableString ss, final Class<? extends CharacterStyle> clz) {
    val array = new JSONArray();
    val spansBg = ss.getSpans(0, ss.length(), clz);
    for (val span : spansBg) {
        int col;
        switch (clz.getSimpleName()) {
            case "BackgroundColorSpan":
                col = ((BackgroundColorSpan) span).getBackgroundColor();
                break;
            case "ForegroundColorSpan":
                col = ((ForegroundColorSpan) span).getForegroundColor();
                break;
            default:
                throw new RuntimeException("Cant match extract class type: " + clz.getSimpleName());
        }
        pullSpanColor(ss, span, col, array);
    }
    return array;
}
 
Example #3
Source File: SpannableSerializer.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private static JSONArray extractClass(final SpannableString ss, final Class<? extends CharacterStyle> clz) {
    val array = new JSONArray();
    val spansBg = ss.getSpans(0, ss.length(), clz);
    for (val span : spansBg) {
        int col;
        switch (clz.getSimpleName()) {
            case "BackgroundColorSpan":
                col = ((BackgroundColorSpan) span).getBackgroundColor();
                break;
            case "ForegroundColorSpan":
                col = ((ForegroundColorSpan) span).getForegroundColor();
                break;
            default:
                throw new RuntimeException("Cant match extract class type: " + clz.getSimpleName());
        }
        pullSpanColor(ss, span, col, array);
    }
    return array;
}
 
Example #4
Source File: ApplicationsDialogPreferenceViewHolderX.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
private void setTextStyle(TextView textView, boolean errorColor)
{
    if (textView != null) {
        CharSequence title = textView.getText();
        Spannable sbt = new SpannableString(title);
        Object[] spansToRemove = sbt.getSpans(0, title.length(), Object.class);
        for (Object span : spansToRemove) {
            if (span instanceof CharacterStyle)
                sbt.removeSpan(span);
        }
        if (errorColor) {
            sbt.setSpan(new ForegroundColorSpan(Color.RED), 0, sbt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        textView.setText(sbt);
    }
}
 
Example #5
Source File: SpansV1.java    From Pioneer with Apache License 2.0 6 votes vote down vote up
@Override
        public void draw(@NonNull Canvas canvas, CharSequence text, @IntRange(from = 0) int start, @IntRange(from = 0) int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
//            bitmapCanvas.drawColor(Color.GRAY, PorterDuff.Mode.CLEAR);
            int color = /*paint instanceof TextPaint ? ((TextPaint) paint).bgColor :*/ paint.getColor();
            bitmapCanvas.drawColor(color);
            for (CharacterStyle style : styles) {
                if (style instanceof ReplacementSpan) {
                    ((ReplacementSpan) style).draw(bitmapCanvas, text, start, end, 0, top, y, bottom, paint);
                } else if (paint instanceof TextPaint) {
                    style.updateDrawState((TextPaint) paint);
                }
            }
            paint.setXfermode(xfermode);
            bitmapCanvas.drawText(text, start, end, 0, y, paint);
            canvas.drawBitmap(bitmap, x, 0, null);
        }
 
Example #6
Source File: ConverterSpannedToHtml.java    From Android-RTEditor with Apache License 2.0 6 votes vote down vote up
private void handleEndTag(CharacterStyle style) {
    if (style instanceof URLSpan) {
        mOut.append("</a>");
    } else if (style instanceof TypefaceSpan) {
        mOut.append("</font>");
    } else if (style instanceof ForegroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof BackgroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof AbsoluteSizeSpan) {
        mOut.append("</font>");
    } else if (style instanceof StrikethroughSpan) {
        mOut.append("</strike>");
    } else if (style instanceof SubscriptSpan) {
        mOut.append("</sub>");
    } else if (style instanceof SuperscriptSpan) {
        mOut.append("</sup>");
    } else if (style instanceof UnderlineSpan) {
        mOut.append("</u>");
    } else if (style instanceof BoldSpan) {
        mOut.append("</b>");
    } else if (style instanceof ItalicSpan) {
        mOut.append("</i>");
    }
}
 
Example #7
Source File: ConverterSpannedToHtml.java    From memoir with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a spanned text within a paragraph
 */
private void withinParagraph(final Spanned text, int start, int end) {
    // create sorted set of CharacterStyles
    SortedSet<CharacterStyle> sortedSpans = new TreeSet<CharacterStyle>(new Comparator<CharacterStyle>() {
        @Override
        public int compare(CharacterStyle s1, CharacterStyle s2) {
            int start1 = text.getSpanStart(s1);
            int start2 = text.getSpanStart(s2);
            if (start1 != start2)
                return start1 - start2;        // span which starts first comes first

            int end1 = text.getSpanEnd(s1);
            int end2 = text.getSpanEnd(s2);
            if (end1 != end2) return end2 - end1;                // longer span comes first

            // if the paragraphs have the same span [start, end] we compare their name
            // compare the name only because local + anonymous classes have no canonical name
            return s1.getClass().getName().compareTo(s2.getClass().getName());
        }
    });
    List<CharacterStyle> spanList = Arrays.asList(text.getSpans(start, end, CharacterStyle.class));
    sortedSpans.addAll(spanList);

    // process paragraphs/divs
    convertText(text, start, end, sortedSpans);
}
 
Example #8
Source File: LinkifyHelper.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
public static <A extends CharacterStyle, B extends CharacterStyle> Spannable replaceAll(
        CharSequence original, Class<A> sourceType, SpanConverter<A, B> converter) {
    SpannableString result = new SpannableString(original);
    A[] spans = result.getSpans(0, result.length(), sourceType);

    for (A span : spans) {
        int start = result.getSpanStart(span);
        int end = result.getSpanEnd(span);
        int flags = result.getSpanFlags(span);

        result.removeSpan(span);
        result.setSpan(converter.convert(span), start, end, flags);
    }

    return (result);
}
 
Example #9
Source File: MarkdownTextChangeWatcher.java    From Elephant with Apache License 2.0 6 votes vote down vote up
/**
     * {@inheritDoc}
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        for (CharacterStyle style: mLastStyle) {
            s.removeSpan(style);
        }
        List<MarkdownSyntaxModel> models = MarkdownSyntaxGenerator.syntaxModelsForString(s.toString());
        if (models.size() == 0) {
            return;
        }
        mLastStyle.clear();
        for (MarkdownSyntaxModel model : models) {
            MarkdownSyntaxType type = model.getSyntaxType();
            Range range = model.getRange();
//            CharacterStyle style = MarkdownSyntaxGenerator.styleFromSyntaxType(type);
            int low = range.getLower();
            int upper = range.getUpper();
//            mLastStyle.add(style);
//            s.setSpan(style, low, upper, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
 
Example #10
Source File: ClonedSpannableString.java    From memoir with Apache License 2.0 6 votes vote down vote up
private void init(CharSequence source, int start, int end) {
    int initial = 20;
    mSpans = new Object[initial];
    mSpanData = new int[initial * 3];

    if (source instanceof Spanned) {
        Spanned sp = (Spanned) source;
        for (Object span : sp.getSpans(start, end, Object.class)) {
            if (span instanceof CharacterStyle || span instanceof ParagraphStyle) {
                int st = sp.getSpanStart(span);
                int en = sp.getSpanEnd(span);
                int fl = sp.getSpanFlags(span);

                if (st < start) st = start;
                if (en > end) en = end;

                setSpan(span, st - start, en - start, fl);
            }
        }
    }
}
 
Example #11
Source File: CustomSpanData.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
@Override
public CharacterStyle onCreateSpan() {
    switch (mSpanType){
            case TYPE_ABS_SIZE_SPAN:
                switch (mUnit){
                        case UNIT_PX:
                            return new AbsoluteSizeSpan((int) mTextSize);
                        case UNIT_SP:
                            return new AbsoluteSizeSpan((int) mTextSize,true);
                }
            case TYPE_CUSTOM_TEXT_SPAN:
                return new CustomTextSpan(mUnit,mTextSize,
                    mTypeface,
                    mColor,
                    mLeftMarginDp,
                    mAlign);

            default:
                return new CustomTextSpan(mUnit,mTextSize,
                    mTypeface,
                    mColor,
                    mLeftMarginDp,
                    mAlign);
    }
}
 
Example #12
Source File: CaptureActivity.java    From android-mrz-reader with Apache License 2.0 6 votes vote down vote up
/**
 * Given either a Spannable String or a regular String and a token, apply
 * the given CharacterStyle to the span between the tokens.
 * <p>
 * NOTE: This method was adapted from:
 * http://www.androidengineer.com/2010/08/easy-method-for-formatting-android.html
 * <p>
 * <p>
 * For example, {@code setSpanBetweenTokens("Hello ##world##!", "##", new
 * ForegroundColorSpan(0xFFFF0000));} will return a CharSequence {@code
 * "Hello world!"} with {@code world} in red.
 */
private CharSequence setSpanBetweenTokens(CharSequence text, String token,
                                          CharacterStyle... cs) {
    // Start and end refer to the points where the span will apply
    int tokenLen = token.length();
    int start = text.toString().indexOf(token) + tokenLen;
    int end = text.toString().indexOf(token, start);

    if (start > -1 && end > -1) {
        // Copy the spannable string to a mutable spannable string
        SpannableStringBuilder ssb = new SpannableStringBuilder(text);
        for (CharacterStyle c : cs)
            ssb.setSpan(c, start, end, 0);
        text = ssb;
    }
    return text;
}
 
Example #13
Source File: Spans.java    From Pioneer with Apache License 2.0 6 votes vote down vote up
@Override
public int getSize(@NonNull Rect outRect, @NonNull Paint paint, CharSequence text, @IntRange(from = 0) int start, @IntRange(from = 0) int end, @Nullable Paint.FontMetricsInt fm) {
    int width = super.getSize(outRect, paint, text, start, end, fm);
    if (styles != null) {
        for (CharacterStyle style : styles) {
            if (style instanceof SupportSpan) {
                width = Math.max(width, ((SupportSpan) style).getSize(frame, paint, text, start, end, fm));
            } else if (style instanceof ReplacementSpan) {
                width = Math.max(width, ((ReplacementSpan) style).getSize(paint, text, start, end, fm));
            } else if (paint instanceof TextPaint) {
                if (style instanceof MetricAffectingSpan) {
                    ((MetricAffectingSpan) style).updateMeasureState((TextPaint) paint);
                }
            }
        }
    }
    frame.right = width;
    return width;
}
 
Example #14
Source File: ClonedSpannableString.java    From Android-RTEditor with Apache License 2.0 6 votes vote down vote up
private void init(CharSequence source, int start, int end) {
    int initial = 20;
    mSpans = new Object[initial];
    mSpanData = new int[initial * 3];

    if (source instanceof Spanned) {
        Spanned sp = (Spanned) source;
        for (Object span : sp.getSpans(start, end, Object.class)) {
            if (span instanceof CharacterStyle || span instanceof ParagraphStyle) {
                int st = sp.getSpanStart(span);
                int en = sp.getSpanEnd(span);
                int fl = sp.getSpanFlags(span);

                if (st < start) st = start;
                if (en > end) en = end;

                setSpan(span, st - start, en - start, fl);
            }
        }
    }
}
 
Example #15
Source File: ConverterSpannedToHtml.java    From Android-RTEditor with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a spanned text within a paragraph
 */
private void withinParagraph(final Spanned text, int start, int end) {
    // create sorted set of CharacterStyles
    SortedSet<CharacterStyle> sortedSpans = new TreeSet<>((s1, s2) -> {
        int start1 = text.getSpanStart(s1);
        int start2 = text.getSpanStart(s2);
        if (start1 != start2)
            return start1 - start2;        // span which starts first comes first

        int end1 = text.getSpanEnd(s1);
        int end2 = text.getSpanEnd(s2);
        if (end1 != end2) return end2 - end1;                // longer span comes first

        // if the paragraphs have the same span [start, end] we compare their name
        // compare the name only because local + anonymous classes have no canonical name
        return s1.getClass().getName().compareTo(s2.getClass().getName());
    });
    List<CharacterStyle> spanList = Arrays.asList(text.getSpans(start, end, CharacterStyle.class));
    sortedSpans.addAll(spanList);

    // process paragraphs/divs
    convertText(text, start, end, sortedSpans);
}
 
Example #16
Source File: ConverterSpannedToHtml.java    From memoir with Apache License 2.0 6 votes vote down vote up
private void handleEndTag(CharacterStyle style) {
    if (style instanceof URLSpan) {
        mOut.append("</a>");
    } else if (style instanceof TypefaceSpan) {
        mOut.append("</font>");
    } else if (style instanceof ForegroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof BackgroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof AbsoluteSizeSpan) {
        mOut.append("</font>");
    } else if (style instanceof StrikethroughSpan) {
        mOut.append("</strike>");
    } else if (style instanceof SubscriptSpan) {
        mOut.append("</sub>");
    } else if (style instanceof SuperscriptSpan) {
        mOut.append("</sup>");
    } else if (style instanceof UnderlineSpan) {
        mOut.append("</u>");
    } else if (style instanceof BoldSpan) {
        mOut.append("</b>");
    } else if (style instanceof ItalicSpan) {
        mOut.append("</i>");
    }
}
 
Example #17
Source File: SpannableSerializer.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private static void pullSpanColor(final SpannableString ss, final CharacterStyle spans, final int colour, final JSONArray array) {
    val jsonObject = new JSONObject();
    try {
        jsonObject.put("c", colour);
        jsonObject.put("s", ss.getSpanStart(spans));
        jsonObject.put("e", ss.getSpanEnd(spans));
    } catch (JSONException e) {
        //
    }
    array.put(jsonObject);
}
 
Example #18
Source File: Truss.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
/** Starts {@code span} at the current position in the builder. */
public Truss pushSpan(Object span) {
    if (span instanceof ReplacementSpan) {
        replacements++;
    } else if (replacements > 0 && span instanceof CharacterStyle) {
        span = convert((CharacterStyle) span);
    }
    stack.addLast(new Span(builder.length(), span));
    return this;
}
 
Example #19
Source File: Iconics.java    From clear-todolist with GNU General Public License v3.0 5 votes vote down vote up
public IconicsBuilderView(Context ctx, List<ITypeface> fonts, TextView view, List<CharacterStyle> styles, HashMap<String, List<CharacterStyle>> stylesFor) {
    this.ctx = ctx;
    this.fonts = fonts;
    this.view = view;
    this.withStyles = styles;
    this.withStylesFor = stylesFor;
}
 
Example #20
Source File: DataWrapper.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
static String getProfileNameWithManualIndicatorAsString(
        Profile profile, boolean addEventName, String indicators, boolean addDuration, boolean multiLine,
        boolean durationInNextLine, DataWrapper dataWrapper) {
    Spannable sProfileName = getProfileNameWithManualIndicator(profile, addEventName, indicators, addDuration, multiLine, durationInNextLine, dataWrapper);
    Spannable sbt = new SpannableString(sProfileName);
    Object[] spansToRemove = sbt.getSpans(0, sProfileName.length(), Object.class);
    for (Object span : spansToRemove) {
        if (span instanceof CharacterStyle)
            sbt.removeSpan(span);
    }
    return sbt.toString();
}
 
Example #21
Source File: Spans.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
@Override
public void draw(@NonNull Rect outRect, @NonNull Canvas canvas, CharSequence text, @IntRange(from = 0) int start, @IntRange(from = 0) int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
    for (CharacterStyle style : styles) {
        if (style instanceof SupportSpan) {
            ((SupportSpan) style).draw(frame, canvas, text, start, end, x, top, y, bottom, paint);
        } else if (style instanceof ReplacementSpan) {
            ((ReplacementSpan) style).draw(canvas, text, start, end, x, top, y, bottom, paint);
        } else if (paint instanceof TextPaint) {
            style.updateDrawState((TextPaint) paint);
        }
    }
}
 
Example #22
Source File: SelectionPopupController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
private boolean hasStyleSpan(Spanned spanned) {
    // Only check against those three classes below, which could affect text appearance, since
    // there are other kind of classes won't affect appearance.
    Class<?>[] styleClasses = {
            CharacterStyle.class, ParagraphStyle.class, UpdateAppearance.class};
    for (Class<?> clazz : styleClasses) {
        if (spanned.nextSpanTransition(-1, spanned.length(), clazz) < spanned.length()) {
            return true;
        }
    }
    return false;
}
 
Example #23
Source File: Spans.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
public ShapeSpan(Shape shape, Paint.Style style, int strokeWidth, @ColorInt int color, boolean includePad, CharacterStyle... styles) {
    super(styles);
    this.shape = shape;
    this.style = style;
    this.strokeWidth = strokeWidth;
    this.color = color;
    this.includePad = includePad;
}
 
Example #24
Source File: Utils.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Formats the app name using "sans-serif" and then appends the summary after a space with
 * "sans-serif-light". Doesn't mandate any font sizes or any other styles, that is up to the
 * {@link android.widget.TextView} which it ends up being displayed in.
 */
public static CharSequence formatAppNameAndSummary(String appName, String summary) {
    String toFormat = appName + ' ' + summary;
    CharacterStyle normal = new TypefaceSpan("sans-serif");
    CharacterStyle light = new TypefaceSpan("sans-serif-light");

    SpannableStringBuilder sb = new SpannableStringBuilder(toFormat);
    sb.setSpan(normal, 0, appName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(light, appName.length(), toFormat.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    return sb;
}
 
Example #25
Source File: CaptchaDialogHelper.java    From talk-android with MIT License 5 votes vote down vote up
private void validCaptcha(final String uid, String value) {
    TalkClient.getInstance().getTbAuthApi()
            .validCaptcha(uid, value)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<ValidCaptchaResponseData>() {
                @Override
                public void call(ValidCaptchaResponseData data) {
                    if (data.isValid() && validSuccessListener != null) {
                        validSuccessListener.onValidSuccess(uid);
                    }
                    if (data.isValid()) {
                        dialog.dismiss();
                    } else {
                        isFailed = true;
                        String contentStr = activity.getString(R.string.content_captcha, captcha.getImageName())
                                + activity.getString(R.string.valid_fail);
                        SpannableStringBuilder ssb = new SpannableStringBuilder(contentStr);
                        ssb.setSpan(CharacterStyle.wrap(new HighlightSpan(activity.getResources())),
                                contentStr.length() - activity.getString(R.string.valid_fail).length(),
                                contentStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        tvContent.setText(ssb);
                        fetchCaptchas();
                    }
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {

                }
            });
}
 
Example #26
Source File: Truss.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
private static MetricAffectingSpan convert(CharacterStyle style) {
    if (style instanceof MetricAffectingSpan) {
        return (MetricAffectingSpan) style;
    } else {
        return new MetricAffectAdapter(style);
    }
}
 
Example #27
Source File: HtmlRawElementStyledText.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
public final void writeTo(@NonNull final SpannableStringBuilder ssb) {

		final int textStart = ssb.length();
		ssb.append(mText);
		final int textEnd = ssb.length();

		if(mSpans != null) {
			for(final CharacterStyle span : mSpans) {
				ssb.setSpan(span, textStart, textEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
			}
		}
	}
 
Example #28
Source File: StringUtil.java    From talk-android with MIT License 5 votes vote down vote up
public static CharSequence getHighlightSpan(String str, String keyword, Resources res) {
    if (str != null && str.length() > 0) {
        SpannableStringBuilder ssb = new SpannableStringBuilder(str);
        if (StringUtil.isBlank(keyword)) {
            return ssb;
        }
        int start;
        if (str.toLowerCase().contains(keyword)) {
            Matcher matcher = Pattern.compile("\\Q" + keyword + "\\E").matcher(str.toLowerCase());
            while (matcher.find()) {
                start = matcher.start();
                int end = matcher.end();
                ssb.setSpan(CharacterStyle.wrap(new HighlightSpan(res)), start, end,
                        Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            }
            return ssb;
        } else if (StringUtil.isChinese(str.charAt(0)) &&
                PinyinUtil.converterToSpell(str).startsWith(keyword)) {
            ssb.setSpan(CharacterStyle.wrap(new HighlightSpan(res)), 0, 1,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            return ssb;
        } else {
            for (int i = 0; i < str.length(); i++) {
                if (PinyinUtil.converterToSpell(str.substring(i, i + 1)).contains(keyword)) {
                    ssb.setSpan(CharacterStyle.wrap(new HighlightSpan(res)), i, i + 1,
                            Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                }
            }
            return ssb;
        }
    } else {
        return "";
    }
}
 
Example #29
Source File: EmphasisTextView.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Override
public void highlight() {

    if (textToHighlight == null) {
        throw new IllegalStateException("You must specify a text to highlight before using executing the highlight operation.");
    }
    if (highlightColor == 0) {
        throw new IllegalStateException("You must specify a color to highlight the text with before using executing the highlight operation.");
    }

    if (!TextUtils.isEmpty(getText()) && !textToHighlight.isEmpty()) {
        String text = getText().toString();
        Spannable spannableString = new SpannableString(text);
        Pattern pattern;
        if (caseInsensitive) {
            pattern = Pattern.compile(Pattern.quote(textToHighlight), Pattern.CASE_INSENSITIVE);
        } else {
            pattern = Pattern.compile(Pattern.quote(textToHighlight));
        }
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            CharacterStyle characterStyle;
            if (highlightMode == HighlightMode.BACKGROUND) {
                characterStyle = new BackgroundColorSpan(highlightColor);
            } else {
                characterStyle = new ForegroundColorSpan(highlightColor);
            }
            spannableString.setSpan(characterStyle, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(spannableString);
    }
}
 
Example #30
Source File: ConverterSpannedToHtml.java    From memoir with Apache License 2.0 5 votes vote down vote up
private void convertText(Spanned text, int start, int end, SortedSet<CharacterStyle> spans) {
    while (start < end) {

        // get first CharacterStyle
        CharacterStyle span = spans.isEmpty() ? null : spans.first();
        int spanStart = span == null ? Integer.MAX_VALUE : text.getSpanStart(span);
        int spanEnd = span == null ? Integer.MAX_VALUE : text.getSpanEnd(span);

        if (start < spanStart) {

            // no paragraph, just plain text
            escape(text, start, Math.min(end, spanStart));
            start = spanStart;

        } else {

            // CharacterStyle found

            spans.remove(span);

            if (handleStartTag(span)) {
                convertText(text, Math.max(spanStart, start), Math.min(spanEnd, end), spans);
            }
            handleEndTag(span);

            start = spanEnd;
        }

    }
}