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 Project: Indic-Keyboard   Author: smc   File: InputTestsBase.java    License: 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 Project: Android-RTEditor   Author: 1gravity   File: ConverterSpannedToHtml.java    License: 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 #3
Source Project: customview-samples   Author: hyhdy   File: CustomSpanData.java    License: 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 #4
Source Project: android-mrz-reader   Author: mercuriete   File: CaptureActivity.java    License: 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 #5
Source Project: Pioneer   Author: baoti   File: Spans.java    License: 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 #6
Source Project: memoir   Author: ronak-manglani   File: ConverterSpannedToHtml.java    License: 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 Project: memoir   Author: ronak-manglani   File: ClonedSpannableString.java    License: 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 #8
Source Project: memoir   Author: ronak-manglani   File: ConverterSpannedToHtml.java    License: 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 #9
Source Project: Pioneer   Author: baoti   File: SpansV1.java    License: 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 #10
Source Project: xDrip   Author: NightscoutFoundation   File: SpannableSerializer.java    License: 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 #11
Source Project: xDrip-plus   Author: jamorham   File: SpannableSerializer.java    License: 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 #12
Source Project: PhoneProfilesPlus   Author: henrichg   File: ApplicationsDialogPreferenceViewHolderX.java    License: 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 #13
Source Project: Android-RTEditor   Author: 1gravity   File: ConverterSpannedToHtml.java    License: 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 #14
Source Project: Zom-Android-XMPP   Author: zom   File: LinkifyHelper.java    License: 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 #15
Source Project: Elephant   Author: Freelander   File: MarkdownTextChangeWatcher.java    License: 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 #16
Source Project: Android-RTEditor   Author: 1gravity   File: ClonedSpannableString.java    License: 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 #17
Source Project: Android-UPnP-Browser   Author: dgmltn   File: SpannableBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public void append(CharSequence seq, int flags, CharacterStyle... whats) {
	int start = mBuilder.length();
	int end = start + seq.length();

	mBuilder.append(seq);

	for (Object what : whats) {
		mBuilder.setSpan(what, start, end, flags);
	}
}
 
Example #18
Source Project: openboard   Author: dslul   File: RichInputConnection.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calls {@link InputConnection#commitText(CharSequence, int)}.
 *
 * @param text The text to commit. This may include styles.
 * @param newCursorPosition The new cursor position around the text.
 */
public void commitText(final CharSequence text, final int newCursorPosition) {
    if (DEBUG_BATCH_NESTING) checkBatchEdit();
    if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
    mCommittedTextBeforeComposingText.append(text);
    // TODO: the following is exceedingly error-prone. Right now when the cursor is in the
    // middle of the composing word mComposingText only holds the part of the composing text
    // that is before the cursor, so this actually works, but it's terribly confusing. Fix this.
    mExpectedSelStart += text.length() - mComposingText.length();
    mExpectedSelEnd = mExpectedSelStart;
    mComposingText.setLength(0);
    if (isConnected()) {
        mTempObjectForCommitText.clear();
        mTempObjectForCommitText.append(text);
        final CharacterStyle[] spans = mTempObjectForCommitText.getSpans(
                0, text.length(), CharacterStyle.class);
        for (final CharacterStyle span : spans) {
            final int spanStart = mTempObjectForCommitText.getSpanStart(span);
            final int spanEnd = mTempObjectForCommitText.getSpanEnd(span);
            final int spanFlags = mTempObjectForCommitText.getSpanFlags(span);
            // We have to adjust the end of the span to include an additional character.
            // This is to avoid splitting a unicode surrogate pair.
            // See org.dslul.openboard.inputmethod.latin.common.Constants.UnicodeSurrogate
            // See https://b.corp.google.com/issues/19255233
            if (0 < spanEnd && spanEnd < mTempObjectForCommitText.length()) {
                final char spanEndChar = mTempObjectForCommitText.charAt(spanEnd - 1);
                final char nextChar = mTempObjectForCommitText.charAt(spanEnd);
                if (UnicodeSurrogate.isLowSurrogate(spanEndChar)
                        && UnicodeSurrogate.isHighSurrogate(nextChar)) {
                    mTempObjectForCommitText.setSpan(span, spanStart, spanEnd + 1, spanFlags);
                }
            }
        }
        mIC.commitText(mTempObjectForCommitText, newCursorPosition);
    }
}
 
Example #19
Source Project: openboard   Author: dslul   File: SuggestionStripLayoutHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static boolean hasStyleSpan(@Nullable final CharSequence text,
        final CharacterStyle style) {
    if (text instanceof Spanned) {
        return ((Spanned)text).getSpanStart(style) >= 0;
    }
    return false;
}
 
Example #20
Source Project: LokiBoard-Android-Keylogger   Author: IceWreck   File: RichInputConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link InputConnection#commitText(CharSequence, int)}.
 *
 * @param text The text to commit. This may include styles.
 * @param newCursorPosition The new cursor position around the text.
 */
public void commitText(final CharSequence text, final int newCursorPosition) {
    if (DEBUG_BATCH_NESTING) checkBatchEdit();
    if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
    mCommittedTextBeforeComposingText.append(text);
    // TODO: the following is exceedingly error-prone. Right now when the cursor is in the
    // middle of the composing word mComposingText only holds the part of the composing text
    // that is before the cursor, so this actually works, but it's terribly confusing. Fix this.
    mExpectedSelStart += text.length() - mComposingText.length();
    mExpectedSelEnd = mExpectedSelStart;
    mComposingText.setLength(0);
    if (isConnected()) {
        mTempObjectForCommitText.clear();
        mTempObjectForCommitText.append(text);
        final CharacterStyle[] spans = mTempObjectForCommitText.getSpans(
                0, text.length(), CharacterStyle.class);
        for (final CharacterStyle span : spans) {
            final int spanStart = mTempObjectForCommitText.getSpanStart(span);
            final int spanEnd = mTempObjectForCommitText.getSpanEnd(span);
            final int spanFlags = mTempObjectForCommitText.getSpanFlags(span);
            // We have to adjust the end of the span to include an additional character.
            // This is to avoid splitting a unicode surrogate pair.
            // See com.abifog.lokiboard.latin.common.Constants.UnicodeSurrogate
            // See https://b.corp.google.com/issues/19255233
            if (0 < spanEnd && spanEnd < mTempObjectForCommitText.length()) {
                final char spanEndChar = mTempObjectForCommitText.charAt(spanEnd - 1);
                final char nextChar = mTempObjectForCommitText.charAt(spanEnd);
                if (UnicodeSurrogate.isLowSurrogate(spanEndChar)
                        && UnicodeSurrogate.isHighSurrogate(nextChar)) {
                    mTempObjectForCommitText.setSpan(span, spanStart, spanEnd + 1, spanFlags);
                }
            }
        }
        mIC.commitText(mTempObjectForCommitText, newCursorPosition);
    }
}
 
Example #21
Source Project: TelePlus-Android   Author: TelePlusDev   File: EditTextCaption.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void applyTextStyleToSelection(TypefaceSpan span) {
    int start;
    int end;
    if (selectionStart >= 0 && selectionEnd >= 0) {
        start = selectionStart;
        end = selectionEnd;
        selectionStart = selectionEnd = -1;
    } else {
        start = getSelectionStart();
        end = getSelectionEnd();
    }
    Editable editable = getText();

    CharacterStyle spans[] = editable.getSpans(start, end, CharacterStyle.class);
    if (spans != null && spans.length > 0) {
        for (int a = 0; a < spans.length; a++) {
            CharacterStyle oldSpan = spans[a];
            int spanStart = editable.getSpanStart(oldSpan);
            int spanEnd = editable.getSpanEnd(oldSpan);
            editable.removeSpan(oldSpan);
            if (spanStart < start) {
                editable.setSpan(oldSpan, spanStart, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (spanEnd > end) {
                editable.setSpan(oldSpan, end, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    if (span != null) {
        editable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    if (delegate != null) {
        delegate.onSpansChanged();
    }
}
 
Example #22
Source Project: mongol-library   Author: suragch   File: MongolTextStorage.java    License: MIT License 5 votes vote down vote up
private void updateGlyphTextForUnicodeRange(int start, int end) {

        if (!(mUnicodeText instanceof Spanned)) return;

        // add spans to glyph string
        CharacterStyle[] spans = ((Spanned) mUnicodeText).getSpans(start, end, CharacterStyle.class);
        for (CharacterStyle span : spans) {
            final int unicodeStart = ((Spanned) mUnicodeText).getSpanStart(span);
            final int unicodeEnd = ((Spanned) mUnicodeText).getSpanEnd(span);
            ((SpannableStringBuilder) mGlyphText).setSpan(span, unicodeStart, unicodeEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
 
Example #23
Source Project: simple-keyboard   Author: rkkr   File: RichInputConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link InputConnection#commitText(CharSequence, int)}.
 *
 * @param text The text to commit. This may include styles.
 * @param newCursorPosition The new cursor position around the text.
 */
public void commitText(final CharSequence text, final int newCursorPosition) {
    if (DEBUG_BATCH_NESTING) checkBatchEdit();
    if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
    mCommittedTextBeforeComposingText.append(text);
    // TODO: the following is exceedingly error-prone. Right now when the cursor is in the
    // middle of the composing word mComposingText only holds the part of the composing text
    // that is before the cursor, so this actually works, but it's terribly confusing. Fix this.
    if (hasCursorPosition()) {
        mExpectedSelStart += text.length() - mComposingText.length();
        mExpectedSelEnd = mExpectedSelStart;
    }
    mComposingText.setLength(0);
    if (isConnected()) {
        mTempObjectForCommitText.clear();
        mTempObjectForCommitText.append(text);
        final CharacterStyle[] spans = mTempObjectForCommitText.getSpans(
                0, text.length(), CharacterStyle.class);
        for (final CharacterStyle span : spans) {
            final int spanStart = mTempObjectForCommitText.getSpanStart(span);
            final int spanEnd = mTempObjectForCommitText.getSpanEnd(span);
            final int spanFlags = mTempObjectForCommitText.getSpanFlags(span);
            // We have to adjust the end of the span to include an additional character.
            // This is to avoid splitting a unicode surrogate pair.
            // See rkr.simplekeyboard.inputmethod.latin.common.Constants.UnicodeSurrogate
            // See https://b.corp.google.com/issues/19255233
            if (0 < spanEnd && spanEnd < mTempObjectForCommitText.length()) {
                final char spanEndChar = mTempObjectForCommitText.charAt(spanEnd - 1);
                final char nextChar = mTempObjectForCommitText.charAt(spanEnd);
                if (UnicodeSurrogate.isLowSurrogate(spanEndChar)
                        && UnicodeSurrogate.isHighSurrogate(nextChar)) {
                    mTempObjectForCommitText.setSpan(span, spanStart, spanEnd + 1, spanFlags);
                }
            }
        }
        mIC.commitText(mTempObjectForCommitText, newCursorPosition);
    }
}
 
Example #24
Source Project: RichEditor   Author: DrownCoder   File: CharacterFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建字号span
 */
private void createSizeSpan(String code, List<CharacterStyle> characterStyles) {
    try {
        if (TextUtils.isEmpty(code) || Integer.parseInt(code) <= 0) return;
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(Integer.parseInt(code));
        characterStyles.add(sizeSpan);
    } catch (NumberFormatException e) {
        Log.e(Const.BASE_LOG, "font size value is not true!");
    }
}
 
Example #25
Source Project: RichEditor   Author: DrownCoder   File: CharacterFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建字色span
 */
private void createColorSpan(String code, List<CharacterStyle> characterStyles) {
    try {
        if (TextUtils.isEmpty(code) || Integer.parseInt(code) == 0) return;
        ForegroundColorSpan foregroundRightColor = new ForegroundColorSpan(Integer.parseInt
                (code));
        characterStyles.add(foregroundRightColor);
    } catch (NumberFormatException e) {
        Log.e(Const.BASE_LOG, "color value is not true!");
    }
}
 
Example #26
Source Project: AOSP-Kayboard-7.1.2   Author: sergchil   File: RichInputConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link InputConnection#commitText(CharSequence, int)}.
 *
 * @param text The text to commit. This may include styles.
 * @param newCursorPosition The new cursor position around the text.
 */
public void commitText(final CharSequence text, final int newCursorPosition) {
    if (DEBUG_BATCH_NESTING) checkBatchEdit();
    if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
    mCommittedTextBeforeComposingText.append(text);
    // TODO: the following is exceedingly error-prone. Right now when the cursor is in the
    // middle of the composing word mComposingText only holds the part of the composing text
    // that is before the cursor, so this actually works, but it's terribly confusing. Fix this.
    mExpectedSelStart += text.length() - mComposingText.length();
    mExpectedSelEnd = mExpectedSelStart;
    mComposingText.setLength(0);
    if (isConnected()) {
        mTempObjectForCommitText.clear();
        mTempObjectForCommitText.append(text);
        final CharacterStyle[] spans = mTempObjectForCommitText.getSpans(
                0, text.length(), CharacterStyle.class);
        for (final CharacterStyle span : spans) {
            final int spanStart = mTempObjectForCommitText.getSpanStart(span);
            final int spanEnd = mTempObjectForCommitText.getSpanEnd(span);
            final int spanFlags = mTempObjectForCommitText.getSpanFlags(span);
            // We have to adjust the end of the span to include an additional character.
            // This is to avoid splitting a unicode surrogate pair.
            // See com.android.inputmethod.latin.common.Constants.UnicodeSurrogate
            // See https://b.corp.google.com/issues/19255233
            if (0 < spanEnd && spanEnd < mTempObjectForCommitText.length()) {
                final char spanEndChar = mTempObjectForCommitText.charAt(spanEnd - 1);
                final char nextChar = mTempObjectForCommitText.charAt(spanEnd);
                if (UnicodeSurrogate.isLowSurrogate(spanEndChar)
                        && UnicodeSurrogate.isHighSurrogate(nextChar)) {
                    mTempObjectForCommitText.setSpan(span, spanStart, spanEnd + 1, spanFlags);
                }
            }
        }
        mIC.commitText(mTempObjectForCommitText, newCursorPosition);
    }
}
 
Example #27
Source Project: AOSP-Kayboard-7.1.2   Author: sergchil   File: SuggestionStripLayoutHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean hasStyleSpan(@Nullable final CharSequence text,
        final CharacterStyle style) {
    if (text instanceof Spanned) {
        return ((Spanned)text).getSpanStart(style) >= 0;
    }
    return false;
}
 
Example #28
Source Project: writeily-pro   Author: plafue   File: Highlighter.java    License: MIT License 5 votes vote down vote up
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]);
        }
    }
 
Example #29
Source Project: talk-android   Author: jianliaoim   File: CaptchaDialogHelper.java    License: MIT License 5 votes vote down vote up
private void fetchCaptchas() {
    adapter.setCaptcha(null);
    progressBar.setVisibility(View.VISIBLE);
    String language = MainApp.PREF_UTIL.getString(Constant.LANGUAGE_PREF, null);
    if (language == null) {
        language = Locale.getDefault().getLanguage();
    }
    TalkClient.getInstance().getTbAuthApi()
            .setUpCaptcha(5, language)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Captcha>() {
                @Override
                public void call(Captcha captcha) {
                    captcha.setLang(TalkClient.getInstance().getLanguage());
                    CaptchaDialogHelper.this.captcha = captcha;
                    progressBar.setVisibility(View.GONE);
                    adapter.setCaptcha(captcha);
                    if (isFailed) {
                        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);
                    } else {
                        tvContent.setText(activity.getString(R.string.content_captcha, captcha.getImageName()));
                    }
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    progressBar.setVisibility(View.GONE);
                }
            });
}
 
Example #30
Source Project: talk-android   Author: jianliaoim   File: CaptchaDialogHelper.java    License: 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) {

                }
            });
}