android.text.style.CharacterStyle

Here are the examples of the java api class android.text.style.CharacterStyle taken from open source projects.

1. RichEditText#disableSpan()

Project: RichEditText
File: RichEditText.java
private void disableSpan(int start, int end, Class<? extends CharacterStyle> clz) {
    CharacterStyle[] spans = mSS.getSpans(start, end, clz);
    for (int i = spans.length - 1; i >= 0; i--) {
        if (mSS.getSpanStart(spans[i]) <= start)
            mSS.setSpan(spans[i], mSS.getSpanStart(spans[i]), start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (mSS.getSpanEnd(spans[i]) > start) {
            mSS.setSpan(spans[i], start, mSS.getSpanEnd(spans[i]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    //mSS.removeSpan(spans[i]);
    }
    mEditText.setText(mSS, TextView.BufferType.SPANNABLE);
    mEditText.setSelection(end);
}

2. RepoListFragment#clickableWelcomeMessage()

Project: agit
File: RepoListFragment.java
private SpannableStringBuilder clickableWelcomeMessage() {
    SpannableStringBuilder message = new SpannableStringBuilder(getString(welcome_message));
    applyToEntireString(message, new TextAppearanceSpan(getActivity(), R.style.WelcomeText));
    final Context applicationContext = getActivity().getApplicationContext();
    CharacterStyle linkStyle = new ForegroundColorSpan(getResources().getColor(R.color.link_text));
    ClickableText.addLinks(message, linkStyle, new ClickableText.Listener() {

        public void onClick(String command, View widget) {
            if (command.equals("clone")) {
                startActivity(new Intent(applicationContext, CloneLauncherActivity.class));
            }
        }
    });
    return message;
}

3. HtmlStyleUtils#clearSpans()

Project: WordPress-Android
File: HtmlStyleUtils.java
/**
     * Clears all relevant spans in {@code content} from {@code start} to {@code end}. Relevant spans are the subclasses
     * of {@link CharacterStyle} applied by {@link HtmlStyleUtils#applySpansByRegex(Spannable, int, int, String)}.
     * @param content the Spannable to clear styles from
     * @param spanStart the index in {@code content} to start clearing styles from
     * @param spanEnd the index in {@code content} to clear styles until
     */
public static void clearSpans(Spannable content, int spanStart, int spanEnd) {
    CharacterStyle[] spans = content.getSpans(spanStart, spanEnd, CharacterStyle.class);
    for (CharacterStyle span : spans) {
        if (span instanceof ForegroundColorSpan || span instanceof StyleSpan || span instanceof RelativeSizeSpan) {
            content.removeSpan(span);
        }
    }
}

4. SpanHelperTest#testReset()

Project: AwesomeValidation
File: SpanHelperTest.java
public void testReset() {
    CharacterStyle mockedSpan1 = mock(CharacterStyle.class);
    Object mockedSpan2 = mock(Object.class);
    CharacterStyle mockedSpan3 = mock(CharacterStyle.class);
    Object[] mockedSpans = new Object[] { mockedSpan1, mockedSpan2, mockedSpan3 };
    when(mMockedEditable.getSpans(0, mMockedEditText.length(), Object.class)).thenReturn(mockedSpans);
    SpanHelper.reset(mMockedEditText);
    verify(mMockedEditable, times(1)).removeSpan(mockedSpan1);
    verify(mMockedEditable, never()).removeSpan(mockedSpan2);
    verify(mMockedEditable, times(1)).removeSpan(mockedSpan3);
}

5. Highlighter#clearSpanType()

Project: writeily-pro
File: Highlighter.java
private <T extends CharacterStyle> void clearSpanType(Editable e, Class<T> spanType) {
    CharacterStyle[] spans = e.getSpans(0, e.length(), spanType);
    for (int n = spans.length; n-- > 0; ) {
        e.removeSpan(spans[n]);
    }
}

6. Styled#drawUniformRun()

Project: TextJustify-Android
File: Styled.java
/**
     * Draws and/or measures a uniform run of text on a single line. No span of
     * interest should start or end in the middle of this run (if not
     * drawing, character spans that don't affect metrics can be ignored).
     * Neither should the run direction change in the middle of the run.
     * 
     * The x position is the leading edge of the text. In a right-to-left
     * paragraph, this will be to the right of the text to be drawn. Paint
     * should not have an Align value other than LEFT or positioning will isCancelled
     * confused.
     * 
     * On return, workPaint will reflect the original paint plus any
     * modifications made by character styles on the run.
     * 
     * The returned width is signed and will be < 0 if the paragraph
     * direction is right-to-left.
     */
private static float drawUniformRun(Canvas canvas, Spanned text, int start, int end, int dir, boolean runIsRtl, float x, int top, int y, int bottom, Paint.FontMetricsInt fmi, TextPaint paint, TextPaint workPaint, boolean needWidth) {
    boolean haveWidth = false;
    float ret = 0;
    CharacterStyle[] spans = text.getSpans(start, end, CharacterStyle.class);
    ReplacementSpan replacement = null;
    // XXX: This shouldn't be modifying paint, only workPaint.
    // However, the members belonging to TextPaint should have default
    // values anyway.  Better to ensure this in the Layout constructor.
    paint.bgColor = 0;
    paint.baselineShift = 0;
    workPaint.set(paint);
    if (spans.length > 0) {
        for (CharacterStyle span : spans) {
            if (span instanceof ReplacementSpan) {
                replacement = (ReplacementSpan) span;
            } else {
                span.updateDrawState(workPaint);
            }
        }
    }
    if (replacement == null) {
        CharSequence tmp;
        int tmpstart, tmpend;
        if (runIsRtl) {
            tmp = TextUtils.getReverse(text, start, end);
            tmpstart = 0;
            // XXX: assumes getReverse doesn't change the length of the text
            tmpend = end - start;
        } else {
            tmp = text;
            tmpstart = start;
            tmpend = end;
        }
        if (fmi != null) {
            workPaint.getFontMetricsInt(fmi);
        }
        if (canvas != null) {
            if (workPaint.bgColor != 0) {
                int c = workPaint.getColor();
                Paint.Style s = workPaint.getStyle();
                workPaint.setColor(workPaint.bgColor);
                workPaint.setStyle(Paint.Style.FILL);
                if (!haveWidth) {
                    ret = workPaint.measureText(tmp, tmpstart, tmpend);
                    haveWidth = true;
                }
                if (dir == Layout.DIR_RIGHT_TO_LEFT) {
                    canvas.drawRect(x - ret, top, x, bottom, workPaint);
                } else {
                    canvas.drawRect(x, top, x + ret, bottom, workPaint);
                }
                workPaint.setStyle(s);
                workPaint.setColor(c);
            }
            if (dir == Layout.DIR_RIGHT_TO_LEFT) {
                if (!haveWidth) {
                    ret = workPaint.measureText(tmp, tmpstart, tmpend);
                    haveWidth = true;
                }
                canvas.drawText(tmp, tmpstart, tmpend, x - ret, y + workPaint.baselineShift, workPaint);
            } else {
                if (needWidth) {
                    if (!haveWidth) {
                        ret = workPaint.measureText(tmp, tmpstart, tmpend);
                        haveWidth = true;
                    }
                }
                canvas.drawText(tmp, tmpstart, tmpend, x, y + workPaint.baselineShift, workPaint);
            }
        } else {
            if (needWidth && !haveWidth) {
                ret = workPaint.measureText(tmp, tmpstart, tmpend);
                haveWidth = true;
            }
        }
    } else {
        ret = replacement.getSize(workPaint, text, start, end, fmi);
        if (canvas != null) {
            if (dir == Layout.DIR_RIGHT_TO_LEFT) {
                replacement.draw(canvas, text, start, end, x - ret, top, y, bottom, workPaint);
            } else {
                replacement.draw(canvas, text, start, end, x, top, y, bottom, workPaint);
            }
        }
    }
    if (dir == Layout.DIR_RIGHT_TO_LEFT) {
        return -ret;
    } else {
        return ret;
    }
}

7. RichEditText#onClick()

Project: RichEditText
File: RichEditText.java
@Override
public void onClick(View view) {
    //refresh tool bar status
    getHtmloptionToolButton();
    mSS = new SpannableStringBuilder(mEditText.getText());
    final int start = mEditText.getSelectionStart();
    final int end = mEditText.getSelectionEnd();
    int viewId = view.getId();
    if (viewId == mEditText.getId()) {
        this.refreshHtmloptionBar();
    }
    CharacterStyle span = null;
    if (viewId == R.id.makeBold) {
        if (toggleImageView((ImageView) view))
            span = new StyleSpan(Typeface.BOLD);
        else
            disableStyleSpan(start, end, Typeface.BOLD);
    } else if (viewId == R.id.makeItalic) {
        if (toggleImageView((ImageView) view))
            span = new StyleSpan(Typeface.ITALIC);
        else
            disableStyleSpan(start, end, Typeface.ITALIC);
    } else if (viewId == R.id.makeUnderline) {
        if (toggleImageView((ImageView) view))
            span = new UnderlineSpan();
        else
            disableSpan(start, end, UnderlineSpan.class);
    } else if (viewId == R.id.makeStrikethrough) {
        if (toggleImageView((ImageView) view))
            span = new StrikethroughSpan();
        else
            disableSpan(start, end, StrikethroughSpan.class);
    } else if (viewId == R.id.makeScaleX && start != end) {
        AbsoluteSizeSpan[] spans = mSS.getSpans(start, end, AbsoluteSizeSpan.class);
        float textSize;
        if (spans.length > 0) {
            textSize = (float) (spans[spans.length - 1].getSize() * 1.1);
        } else {
            textSize = (float) (mEditText.getTextSize() * 1.1);
        }
        for (AbsoluteSizeSpan spanItem : spans) {
            mSS.removeSpan(spanItem);
        }
        span = new AbsoluteSizeSpan((int) textSize);
    } else if (viewId == R.id.makeForeground && start != end) {
        new ColorPickerDialog(_context, new ColorPickerDialog.OnColorChangedListener() {

            @Override
            public void colorChanged(int color) {
                mSS.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mEditText.setText(mSS, TextView.BufferType.SPANNABLE);
            //((TextView)MessageCompose.this.findViewById(R.id.makeForeground)).setTextColor(color);
            }
        }, Color.BLACK).show();
    } else if (viewId == R.id.makeBackground && start != end) {
        new ColorPickerDialog(_context, new ColorPickerDialog.OnColorChangedListener() {

            @Override
            public void colorChanged(int color) {
                mSS.setSpan(new BackgroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mEditText.setText(mSS, TextView.BufferType.SPANNABLE);
            //MessageCompose.this.findViewById(R.id.makeBackground).setBackgroundColor(color);
            }
        }, Color.WHITE).show();
    } else if (viewId == R.id.makeHyperlink && start != end) {
        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
        final EditText urlText = new EditText(_context);
        urlText.setText("http://www.");
        builder.setView(urlText).setTitle(getResources().getString(R.string.url_entry_title)).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
                if (urlText.getText() != null) {
                    String url = urlText.getText().toString();
                    mSS.setSpan(new URLSpan(url), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mEditText.setText(mSS, TextView.BufferType.SPANNABLE);
                }
            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder.create().show();
    } else if (viewId == EDIT_TOGGLE_ID) {
        if (!mToolbarClosed) {
            mToolbarClosed = !mToolbarClosed;
            mImageButton.setRotation(-90);
            //mImageButton.setBackground(getResources().getDrawable(R.drawable.ic_keyboard_arrow_left_black_24dp));
            //                AnimatorSet set = new AnimatorSet();
            //                set.playTogether(
            //                        ObjectAnimator.ofFloat(mHtmloptions, "translationX", mHtmloptions.getMeasuredWidth()),
            //                        ObjectAnimator.ofFloat(mHtmloptions, "alpha", 1, 0)
            //                );
            //                set.start();
            mHtmloptions.setVisibility(View.GONE);
        //requestLayout();
        } else {
            mToolbarClosed = !mToolbarClosed;
            mHtmloptions.setVisibility(View.VISIBLE);
            //requestLayout();
            mImageButton.setRotation(90);
        //                ObjectAnimator objectAnimator = new ObjectAnimator();
        //                AnimatorSet set = new AnimatorSet();
        //                set.playTogether(
        //                        ObjectAnimator.ofFloat(mHtmloptions, "translationX", 0),
        //                        ObjectAnimator.ofFloat(mHtmloptions, "alpha", 0, 1)
        //                );
        //                set.start();
        }
    }
    if (span != null) {
        if (start == end)
            mSS.setSpan(span, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        else
            mSS.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        mEditText.setText(mSS, TextView.BufferType.SPANNABLE);
        mEditText.setSelection(end);
    }
}

8. IconicsUtils#findIcons()

Project: Android-Iconics
File: IconicsUtils.java
/**
     * finds the icons within a Spanned, and tries to map the the available (given via the fonts param) icons on it
     *
     * @param spannable
     * @param fonts
     * @return
     */
public static TextStyleContainer findIcons(Spanned spannable, HashMap<String, ITypeface> fonts) {
    LinkedList<StyleContainer> styleContainers = new LinkedList<>();
    LinkedList<StyleContainer> existingSpans = new LinkedList<>();
    // remember the previous style spans
    for (ParcelableSpan span : spannable.getSpans(0, spannable.length(), ParcelableSpan.class)) {
        existingSpans.add(new StyleContainer(spannable.getSpanStart(span), spannable.getSpanEnd(span), span));
    }
    for (CharacterStyle span : spannable.getSpans(0, spannable.length(), CharacterStyle.class)) {
        existingSpans.add(new StyleContainer(spannable.getSpanStart(span), spannable.getSpanEnd(span), span));
    }
    //the new string built with the replaced icons
    SpannableStringBuilder spannedString = new SpannableStringBuilder();
    SpannableStringBuilder tempIconString = new SpannableStringBuilder();
    for (int i = 0; i < spannable.length(); i++) {
        Character c = spannable.charAt(i);
        if (c == '{') {
            //if something started with { but was no icon replacement
            spannedString.append(tempIconString);
            //start to remember the tempIconString again
            tempIconString = new SpannableStringBuilder();
            tempIconString.append(c);
        } else if (c == '}') {
            tempIconString.append(c);
            //make sure there was a { before and enough chars for the font key
            if (tempIconString.length() > 5) {
                StyleContainer styleContainer = placeFontIcon(spannedString, tempIconString, fonts);
                if (styleContainer != null) {
                    styleContainers.add(styleContainer);
                    //adjust existing spans to new position
                    for (StyleContainer existingStyleContainer : existingSpans) {
                        if (existingStyleContainer.startIndex > i) {
                            existingStyleContainer.startIndex = existingStyleContainer.startIndex - tempIconString.length() + 1;
                        }
                        if (existingStyleContainer.endIndex > i) {
                            existingStyleContainer.endIndex = existingStyleContainer.endIndex - tempIconString.length() + 1;
                        }
                    }
                }
            } else {
                spannedString.append(tempIconString);
            }
            tempIconString = new SpannableStringBuilder();
        } else {
            if (tempIconString.length() == 0) {
                spannedString.append(c);
            } else {
                tempIconString.append(c);
            }
        }
    }
    //make sure to add the last characters which create no complete icon
    spannedString.append(tempIconString);
    //add the existing spans
    styleContainers.addAll(existingSpans);
    return new TextStyleContainer(spannedString, styleContainers);
}

9. IconicsUtils#findIconsFromEditable()

Project: Android-Iconics
File: IconicsUtils.java
/**
     * finds the icons within a Editable, and tries to map the the available (given via the fonts param) icons on it
     * Use this whenever possible, as this method does update the Editable, and does not have to create a new Spanned
     *
     * @param editable
     * @param fonts
     * @return
     */
public static LinkedList<StyleContainer> findIconsFromEditable(Editable editable, HashMap<String, ITypeface> fonts) {
    LinkedList<StyleContainer> styleContainers = new LinkedList<>();
    LinkedList<StyleContainer> existingSpans = new LinkedList<>();
    // remember the previous style spans
    for (ParcelableSpan span : editable.getSpans(0, editable.length(), ParcelableSpan.class)) {
        existingSpans.add(new StyleContainer(editable.getSpanStart(span), editable.getSpanEnd(span), span));
    }
    for (CharacterStyle span : editable.getSpans(0, editable.length(), CharacterStyle.class)) {
        existingSpans.add(new StyleContainer(editable.getSpanStart(span), editable.getSpanEnd(span), span));
    }
    try {
        editable.clearSpans();
    } catch (Exception ex) {
    }
    int iconStart = -1;
    for (int i = 0; i < editable.length(); i++) {
        Character c = editable.charAt(i);
        if (c == '{') {
            iconStart = i;
        } else if (c == '}') {
            if (iconStart > -1) {
                StyleContainer styleContainer = placeFontIcon(editable, iconStart, i, fonts);
                if (styleContainer != null) {
                    styleContainers.add(styleContainer);
                    //adjust existing spans to new position
                    for (StyleContainer existingStyleContainer : existingSpans) {
                        if (existingStyleContainer.startIndex > i) {
                            existingStyleContainer.startIndex = existingStyleContainer.startIndex - (i - iconStart);
                            existingStyleContainer.endIndex = existingStyleContainer.endIndex - (i - iconStart);
                        } else if (existingStyleContainer.endIndex > i) {
                            existingStyleContainer.endIndex = existingStyleContainer.endIndex - (i - iconStart);
                        }
                    }
                    //remember how many chars were removed already so we can remove the correct characters
                    i = i - iconStart;
                }
            }
            iconStart = -1;
        }
    }
    //add the existing spans
    styleContainers.addAll(existingSpans);
    return styleContainers;
}