Java 类android.text.style.BackgroundColorSpan 实例源码

项目:Phoenix-for-VK    文件:PreferencesFragment.java   
private void disableOnlyFullAppPrefs() {
    String fullOnly = " FULL ONLY ";
    int color = Utils.adjustAlpha(CurrentTheme.getColorAccent(getActivity()), 100);

    for (String name : AppPrefs.ONLY_FULL_APP_PREFS) {
        Preference preference = findPreference(name);
        if (preference != null) {
            preference.setEnabled(false);

            CharSequence summary = TextUtils.isEmpty(preference.getTitle()) ? "" : preference.getTitle();
            summary = fullOnly + " " + summary;

            Spannable spannable = SpannableStringBuilder.valueOf(summary);

            BackgroundColorSpan span = new BackgroundColorSpan(color);
            ForegroundColorSpan span1 = new ForegroundColorSpan(Color.WHITE);

            spannable.setSpan(span, 0, fullOnly.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannable.setSpan(span1, 0, fullOnly.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            preference.setTitle(spannable);
        }
    }
}
项目:GSLayout    文件:GSLayoutLine.java   
private void drawBackgroundColor(Canvas canvas) {
    if (!(text instanceof Spanned)) {
        return;
    }
    Spanned spanned = (Spanned) text;
    BackgroundColorSpan[] spans = spanned.getSpans(start, end, BackgroundColorSpan.class);
    if (spans == null || spans.length == 0) {
        return;
    }
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);
    for (BackgroundColorSpan span : spans) {
        RectF spanRect = getRect(span);
        if (spanRect == null) {
            continue;
        }
        spanRect.offset(originX, originY);
        paint.setColor(span.getBackgroundColor());
        canvas.drawRect(spanRect, paint);
    }
}
项目:IslamicLibraryAndroid    文件:SearchResult.java   
public CharSequence getformatedSearchSnippet() {
    //TODO implement improved snippet function
    String CleanedSearchString = " " + ArabicUtilities.cleanTextForSearchingWthStingBuilder(searchString) + " ";
    StringBuilder cleanedUnformattedPage = new StringBuilder(ArabicUtilities.cleanTextForSearchingWthStingBuilder(unformatedPage));
    int firstMatchStart = cleanedUnformattedPage.indexOf(CleanedSearchString);
    cleanedUnformattedPage.delete(0, Math.max(firstMatchStart - 100, 0));
    cleanedUnformattedPage.delete(
            Math.min(firstMatchStart + CleanedSearchString.length() + 100, cleanedUnformattedPage.length())
            , cleanedUnformattedPage.length());
    cleanedUnformattedPage.insert(0, "...");
    cleanedUnformattedPage.append("...");

    Spannable snippet = SpannableString.
            valueOf(cleanedUnformattedPage.toString());
    int index = TextUtils.indexOf(snippet, CleanedSearchString);
    while (index >= 0) {

        snippet.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
                + CleanedSearchString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        index = TextUtils.indexOf(snippet, CleanedSearchString, index + CleanedSearchString.length());
    }

    return snippet;
}
项目:mvvm-template    文件:PreTagHandler.java   
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
    if (isPre) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("\n");//fake padding top + make sure, pre is always by itself
        getPlainText(buffer, node);
        buffer.append("\n");//fake padding bottom + make sure, pre is always by itself
        builder.append(replace(buffer.toString()));
        builder.append("\n");
        builder.setSpan(new CodeBackgroundRoundedSpan(color), start, builder.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append("\n");
        this.appendNewLine(builder);
        this.appendNewLine(builder);
    } else {
        StringBuffer text = node.getText();
        builder.append(" ");
        builder.append(replace(text.toString()));
        builder.append(" ");
        final int stringStart = start + 1;
        final int stringEnd = builder.length() - 1;
        builder.setSpan(new BackgroundColorSpan(color), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
        if (theme == PrefGetter.LIGHT) {
            builder.setSpan(new ForegroundColorSpan(Color.RED), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        builder.setSpan(new TypefaceSpan("monospace"), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
项目:Slide-RSS    文件:SpoilerRobotoTextView.java   
private void setHighlight(SpannableStringBuilder builder, String subreddit) {
    final int offset = "[[h[".length(); // == "]h]]".length()

    int start = -1;
    int end;
    for (int i = 0; i < builder.length() - 4; i++) {
        if (builder.charAt(i) == '['
                && builder.charAt(i + 1) == '['
                && builder.charAt(i + 2) == 'h'
                && builder.charAt(i + 3) == '[') {
            start = i + offset;
        } else if (builder.charAt(i) == ']'
                && builder.charAt(i + 1) == 'h'
                && builder.charAt(i + 2) == ']'
                && builder.charAt(i + 3) == ']') {
            end = i;
            builder.setSpan(new BackgroundColorSpan(Palette.getColor(subreddit)), start, end,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            builder.delete(end, end + offset);
            builder.delete(start - offset, start);
            i -= offset + (end - start); // length of text
        }
    }
}
项目:AndroidSnooper    文件:EspressoViewMatchers.java   
public static Matcher<View> hasBackgroundSpanOn(final String text, @ColorRes final int colorResource) {
  return new CustomTypeSafeMatcher<View>("") {
    @Override
    protected boolean matchesSafely(View view) {
      if (view == null || !(view instanceof TextView))
        return false;
      SpannableString spannableString = (SpannableString) ((TextView) view).getText();
      BackgroundColorSpan[] spans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);
      for (BackgroundColorSpan span : spans) {
        int start = spannableString.getSpanStart(span);
        int end = spannableString.getSpanEnd(span);
        CharSequence highlightedString = spannableString.subSequence(start, end);
        if (text.equals(highlightedString.toString())) {
          return span.getBackgroundColor() == view.getContext().getResources().getColor(colorResource);
        }
      }
      return false;
    }
  };
}
项目:ChenYan    文件:Main2Activity.java   
private void spanTest() {
        SpannableString spannableString = new SpannableString("欢迎光临我的博客");
//        字体颜色span
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.BLUE);
//        背景颜色span
        BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.RED);

//        1,3其实是两个位置,末尾不包括
//        Flag 为 span如果新增了文字 的前面不包括样式,后面包括样式
        spannableString.setSpan(colorSpan, 1, 3, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableString.setSpan(backgroundColorSpan, 5, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(spannableString);

        editText.setText(spannableString);

    }
项目:SimpleDialogFragments    文件:AdvancedAdapter.java   
/**
 * Highlights everything that matched the current filter (if any) in text
 *
 * @param text the text to highlight
 * @param color the highlight color
 * @return a spannable string
 */
protected Spannable highlight(String text, int color) {
    if (text == null) return null;

    Spannable highlighted = new SpannableStringBuilder(text);
    AdvancedFilter filter = getFilter();

    if (filter == null || filter.mPattern == null){
        return highlighted;
    }

    Matcher matcher = filter.mPattern.matcher(text);

    while (matcher.find()){
        highlighted.setSpan(new BackgroundColorSpan(color), matcher.start(),
                matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }

    return highlighted;
}
项目:revolution-irc    文件:TextFormatBar.java   
protected ColorListPickerDialog createColorPicker(boolean fillColor, int selectedColor) {
    ColorListPickerDialog dialog = new ColorListPickerDialog(getContext());
    if (!fillColor) {
        dialog.setTitle(R.string.format_text_color);
    } else {
        dialog.setTitle(R.string.format_fill_color);
    }
    dialog.setSelectedColor(selectedColor);
    dialog.setPositiveButton(R.string.action_cancel, null);
    dialog.setOnColorChangeListener((ColorListPickerDialog d, int newColorIndex, int color) -> {
        if (!fillColor) {
            removeSpan(ForegroundColorSpan.class);
            setSpan(new ForegroundColorSpan(color));
        } else {
            removeSpan(BackgroundColorSpan.class);
            setSpan(new BackgroundColorSpan(color));
        }
        d.cancel();
    });
    return dialog;
}
项目:revolution-irc    文件:SpannableStringHelper.java   
public static JsonObject spanToJson(Object span) {
    JsonObject ret = new JsonObject();
    if (span instanceof ForegroundColorSpan) {
        ret.addProperty("type", SPAN_TYPE_FOREGROUND);
        ret.addProperty("color", ((ForegroundColorSpan) span).getForegroundColor());
    } else if (span instanceof BackgroundColorSpan) {
        ret.addProperty("type", SPAN_TYPE_BACKGROUND);
        ret.addProperty("color", ((BackgroundColorSpan) span).getBackgroundColor());
    } else if (span instanceof StyleSpan) {
        ret.addProperty("type", SPAN_TYPE_STYLE);
        ret.addProperty("style", ((StyleSpan) span).getStyle());
    } else {
        return null;
    }
    return ret;
}
项目:HtmlCompat    文件:HtmlToSpannedConverter.java   
private void endCssStyle(String tag, Editable text) {
    Strikethrough s = getLast(text, Strikethrough.class);
    if (s != null) {
        setSpanFromMark(tag, text, s, new StrikethroughSpan());
    }
    Background b = getLast(text, Background.class);
    if (b != null) {
        setSpanFromMark(tag, text, b, new BackgroundColorSpan(b.mBackgroundColor));
    }
    Foreground f = getLast(text, Foreground.class);
    if (f != null) {
        setSpanFromMark(tag, text, f, new ForegroundColorSpan(f.mForegroundColor));
    }
    AbsoluteSize a = getLast(text, AbsoluteSize.class);
    if (a != null) {
        setSpanFromMark(tag, text, a, new AbsoluteSizeSpan(a.getTextSize()));
    }
    RelativeSize r = getLast(text, RelativeSize.class);
    if (r != null) {
        setSpanFromMark(tag, text, r, new RelativeSizeSpan(r.getTextProportion()));
    }
}
项目:firefox-tv    文件:InlineAutocompleteEditText.java   
/**
 * Reset autocomplete states to their initial values
 */
private void resetAutocompleteState() {
    mAutoCompleteSpans = new Object[] {
            // Span to mark the autocomplete text
            AUTOCOMPLETE_SPAN,
            // Span to change the autocomplete text color
            new BackgroundColorSpan(
                    ContextCompat.getColor(getContext(), R.color.colorAccent))
    };

    mAutoCompleteResult = AutocompleteResult.emptyResult();

    // Pretend we already autocompleted the existing text,
    // so that actions like backspacing don't trigger autocompletion.
    mAutoCompletePrefixLength = getText().length();

    // Show the cursor.
    setCursorVisible(true);
}
项目:AOSP-Kayboard-7.1.2    文件:InputLogic.java   
/**
 * Equivalent to {@link #setComposingTextInternal(CharSequence, int)} except that this method
 * allows to set {@link BackgroundColorSpan} to the composing text with the given color.
 *
 * <p>TODO: Currently the background color is exclusive with the black underline, which is
 * automatically added by the framework. We need to change the framework if we need to have both
 * of them at the same time.</p>
 * <p>TODO: Should we move this method to {@link RichInputConnection}?</p>
 *
 * @param newComposingText the composing text to be set
 * @param newCursorPosition the new cursor position
 * @param backgroundColor the background color to be set to the composing text. Set
 * {@link Color#TRANSPARENT} to disable the background color.
 * @param coloredTextLength the length of text, in Java chars, which should be rendered with
 * the given background color.
 */
private void setComposingTextInternalWithBackgroundColor(final CharSequence newComposingText,
        final int newCursorPosition, final int backgroundColor, final int coloredTextLength) {
    final CharSequence composingTextToBeSet;
    if (backgroundColor == Color.TRANSPARENT) {
        composingTextToBeSet = newComposingText;
    } else {
        final SpannableString spannable = new SpannableString(newComposingText);
        final BackgroundColorSpan backgroundColorSpan =
                new BackgroundColorSpan(backgroundColor);
        final int spanLength = Math.min(coloredTextLength, spannable.length());
        spannable.setSpan(backgroundColorSpan, 0, spanLength,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
        composingTextToBeSet = spannable;
    }
    mConnection.setComposingText(composingTextToBeSet, newCursorPosition);
}
项目:YellowNote    文件:EditActivity.java   
/**
     * 将匹配的字符设置背景色
     *
     * @param target  目标字符
     * @param content 全体字符
     * @return 设置好背景色的text
     */
    public Spannable replace(String target, String content) {
        Spannable spanText = new SpannableString(content);
//        int index = -1;
        for (Integer i : searchResult) {
            spanText.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.minionYellow))
                    , i, i + target.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
//        while (content.indexOf(target, index + 1) != -1) {
//            index = content.indexOf(target, index + 1);
//            spanText.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.minionYellow))
//                    , index, index + target.length(),
//                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        }
        return spanText;
    }
项目:rview    文件:AsyncTextDiffProcessor.java   
private void processNoIntralineDataA(
        DiffContentInfo diff, DiffInfoModel m, String line, int color) {
    final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
    if (diff.a != null && diff.b != null
            && diff.a.length == 1 && diff.b.length == 1) {
        Spannable span = spannableFactory.newSpannable(prepareTabs(line));
        int z = diff.a[0].indexOf(diff.b[0]);
        if (z != -1) {
            if (z > 0) {
                span.setSpan(new BackgroundColorSpan(color),
                        0, z, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (z + diff.b[0].length() < diff.a[0].length()) {
                z = z + diff.b[0].length();
                span.setSpan(new BackgroundColorSpan(color),
                        z, diff.a[0].length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        m.lineA = span;
    } else {
        m.lineA = prepareTabs(line);
    }
}
项目:rview    文件:AsyncTextDiffProcessor.java   
private void processNoIntralineDataB(
        DiffContentInfo diff, DiffInfoModel m, String line, int color) {
    final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
    if (diff.a != null && diff.b != null
            && diff.a.length == 1 && diff.b.length == 1) {
        Spannable span = spannableFactory.newSpannable(prepareTabs(line));
        int z = diff.b[0].indexOf(diff.a[0]);
        if (z != -1) {
            if (z > 0) {
                span.setSpan(new BackgroundColorSpan(color),
                        0, z, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (z + diff.a[0].length() < diff.b[0].length()) {
                z = z + diff.a[0].length();
                span.setSpan(new BackgroundColorSpan(color),
                        z, diff.b[0].length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        m.lineB = span;
    } else {
        m.lineB = prepareTabs(line);
    }
}
项目:rview    文件:AsyncTextDiffProcessor.java   
private CharSequence processHighlightTrailingSpaces(CharSequence text) {
    final Context context = mContext.get();
    if (context == null) {
        return text;
    }

    if (!mHighlightTrailingWhitespaces) {
        return text;
    }

    int color = ContextCompat.getColor(context, R.color.diffHighlightColor);
    final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
    String line = text.toString();
    final Matcher matcher = HIGHLIGHT_TRAIL_SPACES_PATTERN.matcher(line);
    if (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        Spannable span = spannableFactory.newSpannable(text);
        span.setSpan(new BackgroundColorSpan(color),
                start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    }
    return text;
}
项目:focus-android    文件:InlineAutocompleteEditText.java   
/**
 * Reset autocomplete states to their initial values
 */
private void resetAutocompleteState() {
    mAutoCompleteSpans = new Object[] {
            // Span to mark the autocomplete text
            AUTOCOMPLETE_SPAN,
            // Span to change the autocomplete text color
            new BackgroundColorSpan(
                    ContextCompat.getColor(getContext(), R.color.colorAccent))
    };

    mAutoCompleteResult = AutocompleteResult.emptyResult();

    // Pretend we already autocompleted the existing text,
    // so that actions like backspacing don't trigger autocompletion.
    mAutoCompletePrefixLength = getText().length();

    // Show the cursor.
    setCursorVisible(true);
}
项目:ScribaNotesApp    文件:EditNoteActivity.java   
public void clearTitle() {

        ssbTitle = (SpannableStringBuilder) noteTitleText.getText();
        StyleSpan[] ss = ssbTitle.getSpans(noteTitleText.getSelectionStart(), noteTitleText.getSelectionEnd(), StyleSpan.class);
        UnderlineSpan[] us = ssbTitle.getSpans(noteTitleText.getSelectionStart(), noteTitleText.getSelectionEnd(), UnderlineSpan.class);
        BackgroundColorSpan[] bgSpan = ssbTitle.getSpans(noteTitleText.getSelectionStart(), noteTitleText.getSelectionEnd(), BackgroundColorSpan.class);

        for (int i = 0; i < bgSpan.length; i++) {
            ssbTitle.removeSpan(bgSpan[i]);
        }

        for (int i = 0; i < ss.length; i++) {
            if (ss[i].getStyle() == Typeface.BOLD_ITALIC || ss[i].getStyle() == Typeface.BOLD || ss[i].getStyle() == Typeface.ITALIC) {
                ssbTitle.removeSpan(ss[i]);
            }
        }

        for (int i = 0; i < us.length; i++) {
            ssbTitle.removeSpan(us[i]);
        }

        noteTitleText.setText(ssbTitle);

    }
项目:ScribaNotesApp    文件:EditNoteActivity.java   
public void clearContent() {

        ssbContent = (SpannableStringBuilder) noteContentText.getText();
        StyleSpan[] ss = ssbContent.getSpans(noteContentText.getSelectionStart(), noteContentText.getSelectionEnd(), StyleSpan.class);
        UnderlineSpan[] us = ssbContent.getSpans(noteContentText.getSelectionStart(), noteContentText.getSelectionEnd(), UnderlineSpan.class);
        BackgroundColorSpan[] bgSpan = ssbContent.getSpans(noteContentText.getSelectionStart(), noteContentText.getSelectionEnd(), BackgroundColorSpan.class);

        for (int i = 0; i < ss.length; i++) {
            if (ss[i].getStyle() == Typeface.BOLD_ITALIC || ss[i].getStyle() == Typeface.BOLD || ss[i].getStyle() == Typeface.ITALIC) {
                ssbContent.removeSpan(ss[i]);
            }
        }

        for (int i = 0; i < us.length; i++) {
            ssbContent.removeSpan(us[i]);
        }

        for (int i = 0; i < bgSpan.length; i++) {
            ssbContent.removeSpan(bgSpan[i]);
        }

        noteContentText.setText(ssbContent);
    }
项目:ForPDA    文件:Html.java   
private static void endCssStyle(Editable text) {
    Font font = getLast(text, Font.class);
    if (font != null) {
        if (font.mFace.equalsIgnoreCase("fontello")) {
            setSpanFromMark(text, font, new AssetsTypefaceSpan(App.getContext(), "fontello/fontello.ttf"));
        }
    }
    Strikethrough s = getLast(text, Strikethrough.class);
    if (s != null) {
        setSpanFromMark(text, s, new StrikethroughSpan());
    }
    Background b = getLast(text, Background.class);
    if (b != null) {
        setSpanFromMark(text, b, new BackgroundColorSpan(b.mBackgroundColor));
    }
    Foreground f = getLast(text, Foreground.class);
    if (f != null) {
        setSpanFromMark(text, f, new ForegroundColorSpan(f.mForegroundColor));
    }

}
项目:memoir    文件:ConverterSpannedToHtml.java   
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>");
    }
}
项目:memoir    文件:ConverterSpannedToHtml.java   
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>");
    }
}
项目:videoPickPlayer    文件:WebvttDecoderTest.java   
public void testWebvttWithCssStyle() throws IOException, SubtitleDecoderException {
  WebvttSubtitle subtitle = getSubtitleForTestAsset(WITH_CSS_STYLES);

  // Test event count.
  assertEquals(8, subtitle.getEventTimeCount());

  // Test cues.
  assertCue(subtitle, 0, 0, 1234000, "This is the first subtitle.");
  assertCue(subtitle, 2, 2345000, 3456000, "This is the second subtitle.");

  Spanned s1 = getUniqueSpanTextAt(subtitle, 0);
  Spanned s2 = getUniqueSpanTextAt(subtitle, 2345000);
  Spanned s3 = getUniqueSpanTextAt(subtitle, 20000000);
  Spanned s4 = getUniqueSpanTextAt(subtitle, 25000000);
  assertEquals(1, s1.getSpans(0, s1.length(), ForegroundColorSpan.class).length);
  assertEquals(1, s1.getSpans(0, s1.length(), BackgroundColorSpan.class).length);
  assertEquals(2, s2.getSpans(0, s2.length(), ForegroundColorSpan.class).length);
  assertEquals(1, s3.getSpans(10, s3.length(), UnderlineSpan.class).length);
  assertEquals(2, s4.getSpans(0, 16, BackgroundColorSpan.class).length);
  assertEquals(1, s4.getSpans(17, s4.length(), StyleSpan.class).length);
  assertEquals(Typeface.BOLD, s4.getSpans(17, s4.length(), StyleSpan.class)[0].getStyle());
}
项目:SimpleDialogFragments    文件:AdvancedAdapter.java   
/**
 * Highlights everything that matched the current filter (if any) in text
 *
 * @param text the text to highlight
 * @param color the highlight color
 * @return a spannable string
 */
protected Spannable highlight(String text, int color) {
    if (text == null) return null;

    Spannable highlighted = new SpannableStringBuilder(text);
    AdvancedFilter filter = getFilter();

    if (filter == null || filter.mPattern == null){
        return highlighted;
    }

    Matcher matcher = filter.mPattern.matcher(text);

    while (matcher.find()){
        highlighted.setSpan(new BackgroundColorSpan(color), matcher.start(),
                matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }

    return highlighted;
}
项目:S1-Next    文件:HtmlTagHandlerCompat.java   
private static void endCssStyle(Editable text) {
    Strikethrough s = getLast(text, Strikethrough.class);
    if (s != null) {
        setSpanFromMark(text, s, new StrikethroughSpan());
    }

    Background b = getLast(text, Background.class);
    if (b != null) {
        setSpanFromMark(text, b, new BackgroundColorSpan(b.mBackgroundColor));
    }

    Foreground f = getLast(text, Foreground.class);
    if (f != null) {
        setSpanFromMark(text, f, new ForegroundColorSpan(f.mForegroundColor));
    }
}
项目:Better-Link-Movement-Method    文件:BetterLinkMovementMethod.java   
/**
 * Removes the highlight color under the Url.
 */
protected void removeUrlHighlightColor(TextView textView) {
  if (!isUrlHighlighted) {
    return;
  }
  isUrlHighlighted = false;

  final Spannable text = (Spannable) textView.getText();

  BackgroundColorSpan[] highlightSpans = text.getSpans(0, text.length(), BackgroundColorSpan.class);
  for (BackgroundColorSpan highlightSpan : highlightSpans) {
    text.removeSpan(highlightSpan);
  }

  textView.setText(text);

  Selection.removeSelection(text);
}
项目:Doctor    文件:ConverterSpannedToHtml.java   
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>");
    }
}
项目:Android-RTEditor    文件:ConverterSpannedToHtml.java   
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>");
    }
}
项目:365browser    文件:ImeAdapter.java   
@CalledByNative
private void populateUnderlinesFromSpans(CharSequence text, long underlines) {
    if (DEBUG_LOGS) {
        Log.i(TAG, "populateUnderlinesFromSpans: text [%s], underlines [%d]", text, underlines);
    }
    if (!(text instanceof SpannableString)) return;

    SpannableString spannableString = ((SpannableString) text);
    CharacterStyle spans[] =
            spannableString.getSpans(0, text.length(), CharacterStyle.class);
    for (CharacterStyle span : spans) {
        if (span instanceof BackgroundColorSpan) {
            nativeAppendBackgroundColorSpan(underlines, spannableString.getSpanStart(span),
                    spannableString.getSpanEnd(span),
                    ((BackgroundColorSpan) span).getBackgroundColor());
        } else if (span instanceof UnderlineSpan) {
            nativeAppendUnderlineSpan(underlines, spannableString.getSpanStart(span),
                    spannableString.getSpanEnd(span));
        }
    }
}
项目:transistor    文件:WebvttDecoderTest.java   
public void testWebvttWithCssStyle() throws IOException, SubtitleDecoderException {
  WebvttSubtitle subtitle = getSubtitleForTestAsset(WITH_CSS_STYLES);

  // Test event count.
  assertEquals(8, subtitle.getEventTimeCount());

  // Test cues.
  assertCue(subtitle, 0, 0, 1234000, "This is the first subtitle.");
  assertCue(subtitle, 2, 2345000, 3456000, "This is the second subtitle.");

  Spanned s1 = getUniqueSpanTextAt(subtitle, 0);
  Spanned s2 = getUniqueSpanTextAt(subtitle, 2345000);
  Spanned s3 = getUniqueSpanTextAt(subtitle, 20000000);
  Spanned s4 = getUniqueSpanTextAt(subtitle, 25000000);
  assertEquals(1, s1.getSpans(0, s1.length(), ForegroundColorSpan.class).length);
  assertEquals(1, s1.getSpans(0, s1.length(), BackgroundColorSpan.class).length);
  assertEquals(2, s2.getSpans(0, s2.length(), ForegroundColorSpan.class).length);
  assertEquals(1, s3.getSpans(10, s3.length(), UnderlineSpan.class).length);
  assertEquals(2, s4.getSpans(0, 16, BackgroundColorSpan.class).length);
  assertEquals(1, s4.getSpans(17, s4.length(), StyleSpan.class).length);
  assertEquals(Typeface.BOLD, s4.getSpans(17, s4.length(), StyleSpan.class)[0].getStyle());
}
项目:Overchan-Android    文件:HtmlParser.java   
private static List<Object> parseStyleAttributes(String style) {
    if (TextUtils.isEmpty(style)) return Collections.emptyList();
    int foregroundColor = 0, backgroundColor = 0;
    String[] cssStyle = style.split("[;]");
    for (String s : cssStyle) {
        int color = parseColor(s);
        if (color != 0) {
            if (s.toLowerCase(Locale.US).indexOf("background") != -1) backgroundColor = color; else foregroundColor = color;
        }
    }
    if (foregroundColor == 0 && backgroundColor == 0) {
        return Collections.emptyList();
    } else if (backgroundColor == 0) {
        return Collections.singletonList((Object) new ForegroundColorSpan(foregroundColor));
    } else if (foregroundColor == 0) {
        return Collections.singletonList((Object) new BackgroundColorSpan(backgroundColor));
    } else {
        List<Object> spans = new ArrayList<Object>(2);
        spans.add(new ForegroundColorSpan(foregroundColor));
        spans.add(new BackgroundColorSpan(backgroundColor));
        return spans;
    }
}
项目:CountdownButton    文件:CustomProviderActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_provider);
    this.countdownButton = (CountdownButton) findViewById(R.id.countdown_button);

    countdownButton.setCountdownProvider(new CountdownButton.IProvider() {
        @NonNull
        @Override
        public CharSequence getCountdownText(long millisUntilFinished, int timeUnit) {
            SpannableString spannableString = new SpannableString("CUSTOM TEXT" + millisUntilFinished / 1000);

            int index = (int) (millisUntilFinished / 1000 % spannableString.length());
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CustomProviderActivity.this, R.color.colorPrimary)), index, index + 1, Spanned.SPAN_USER);
            int index2 = (int) (millisUntilFinished / 500 % spannableString.length());
            spannableString.setSpan(new BackgroundColorSpan(ContextCompat.getColor(CustomProviderActivity.this, R.color.colorAccent)), index2, index2 + 1, Spanned.SPAN_USER);

            return spannableString;
        }
    });
}
项目:mc_backup    文件:ToolbarEditText.java   
/**
 * Reset autocomplete states to their initial values
 */
private void resetAutocompleteState() {
    mAutoCompleteSpans = new Object[] {
        // Span to mark the autocomplete text
        AUTOCOMPLETE_SPAN,
        // Span to change the autocomplete text color
        new BackgroundColorSpan(getHighlightColor())
    };

    mAutoCompleteResult = "";

    // Pretend we already autocompleted the existing text,
    // so that actions like backspacing don't trigger autocompletion.
    mAutoCompletePrefixLength = getText().length();

    // Show the cursor.
    setCursorVisible(true);
}
项目:Dashchan    文件:ViewUnit.java   
private CharSequence makeHighlightedText(CharSequence text) {
    if (highlightText != null && text != null) {
        Locale locale = Locale.getDefault();
        SpannableString spannable = new SpannableString(text);
        String searchable = text.toString().toLowerCase(locale);
        for (String highlight : highlightText) {
            highlight = highlight.toLowerCase(locale);
            int textIndex = -1;
            while ((textIndex = searchable.indexOf(highlight, textIndex + 1)) >= 0) {
                spannable.setSpan(new BackgroundColorSpan(uiManager.getColorScheme().highlightTextColor),
                        textIndex, textIndex + highlight.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            text = spannable;
        }
    }
    return text;
}
项目:Slide    文件:SpoilerRobotoTextView.java   
private void setHighlight(SpannableStringBuilder builder, String subreddit) {
    final int offset = "[[h[".length(); // == "]h]]".length()

    int start = -1;
    int end;
    for (int i = 0; i < builder.length() - 4; i++) {
        if (builder.charAt(i) == '['
                && builder.charAt(i + 1) == '['
                && builder.charAt(i + 2) == 'h'
                && builder.charAt(i + 3) == '[') {
            start = i + offset;
        } else if (builder.charAt(i) == ']'
                && builder.charAt(i + 1) == 'h'
                && builder.charAt(i + 2) == ']'
                && builder.charAt(i + 3) == ']') {
            end = i;
            builder.setSpan(new BackgroundColorSpan(Palette.getColor(subreddit)), start, end,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            builder.delete(end, end + offset);
            builder.delete(start - offset, start);
            i -= offset + (end - start); // length of text
        }
    }
}
项目:ProjectX    文件:SpannableStringBuilderUtil.java   
/**
 * 获取SpannableStringBuilder
 *
 * @param text       字符串源
 * @param color      颜色
 * @param foreground 是否为前景
 * @param value      修改的文字
 * @return SpannableStringBuilder
 */
public static SpannableStringBuilder getSpannableStringBuilder(String text, int color,
                                                               boolean foreground,
                                                               String value) {
    SpannableStringBuilder style = new SpannableStringBuilder(text);
    int start;
    int end = 0;
    final int count = text.length();
    while (end < count) {
        start = text.indexOf(value, end);
        if (start == -1) {
            break;
        }
        end = start + value.length();
        if (foreground) {
            style.setSpan(
                    new ForegroundColorSpan(color), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            style.setSpan(
                    new BackgroundColorSpan(color), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return style;
}
项目:android_career    文件:NoteEditActivity.java   
private Spannable getHighlightQueryResult(String fullText, String userQuery) {
    SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
    if (!TextUtils.isEmpty(userQuery)) {
        mPattern = Pattern.compile(userQuery);
        Matcher m = mPattern.matcher(fullText);
        int start = 0;
        while (m.find(start)) {
            spannable.setSpan(
                    new BackgroundColorSpan(this.getResources().getColor(
                            R.color.user_query_highlight)), m.start(), m.end(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            start = m.end();
        }
    }
    return spannable;
}
项目:LWPTools    文件:ColorPref.java   
public static CharSequence createBlendedColorSummary(int start, int end, String label){
    if (label == null)
        label = " ";
    //space, then label, then 10 blend spaces, then 2 of end color
    Spannable summary = new SpannableString ( " " + label + "          " + "  ");
    int[] blendColors = new int[11]; //[0] won't be used because same color as start color
    for (int i=0;i<blendColors.length;i++){
        float fraction = (float)i/(float)blendColors.length;
        blendColors[i]=ColorUtil.blendAndroidIntsPreservingLerpedSaturation(start, end, fraction);
    }

    summary.setSpan( new BackgroundColorSpan( start ), 0, 1+label.length(), 0 );
    for (int i=1;i<blendColors.length;i++){
        int first = label.length() + i;
        summary.setSpan( new BackgroundColorSpan( blendColors[i] ), first, first+1, 0 );
    }
    summary.setSpan( new BackgroundColorSpan( end ), summary.length()-2, summary.length(), 0 );

    float[] hsv = new float[3];
    Color.colorToHSV(start, hsv);
    summary.setSpan( new ForegroundColorSpan( hsv[2]<0.30f ? Color.WHITE : Color.BLACK ), 0, summary.length(), 0 );

    return summary;
}
项目:LWPTools    文件:ColorPref.java   
public static CharSequence createNarrowBlendedColorSummary(int start, int end, String label){
    if (label == null)
        label = " ";
    //space, then label, then 5 blend spaces, then 1 of end color
    Spannable summary = new SpannableString ( " " + label + "     " + " ");
    int[] blendColors = new int[6]; //[0] won't be used because same color as start color
    for (int i=0;i<blendColors.length;i++){
        float fraction = (float)i/(float)blendColors.length;
        blendColors[i]= ColorUtil.blendAndroidIntsPreservingLerpedSaturation(start, end, fraction);
    }

    summary.setSpan( new BackgroundColorSpan( start ), 0, 1+label.length(), 0 );
    for (int i=1;i<blendColors.length;i++){
        int first = label.length() + i;
        summary.setSpan( new BackgroundColorSpan( blendColors[i] ), first, first+1, 0 );
    }
    summary.setSpan( new BackgroundColorSpan( end ), summary.length()-1, summary.length(), 0 );

    float[] hsv = new float[3];
    Color.colorToHSV(start, hsv);
    summary.setSpan( new ForegroundColorSpan( hsv[2]<0.30f ? Color.WHITE : Color.BLACK ), 0, summary.length(), 0 );

    return summary;
}