android.text.Spanned Java Examples

The following examples show how to use android.text.Spanned. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WordTokenizer.java    From Spyglass with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the index of the end of the last span before the cursor or
 * the start of the current line if there are no spans before the cursor.
 *
 * @param text   the {@link Spanned} to examine
 * @param cursor position of the cursor in text
 *
 * @return the furthest in front of the cursor to search for the current keywords
 */
protected int getSearchStartIndex(final @NonNull Spanned text, int cursor) {
    if (cursor < 0 || cursor > text.length()) {
        cursor = 0;
    }

    // Get index of the end of the last span before the cursor (or 0 if does not exist)
    MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class);
    int closestToCursor = 0;
    for (MentionSpan span : spans) {
        int end = text.getSpanEnd(span);
        if (end > closestToCursor && end <= cursor) {
            closestToCursor = end;
        }
    }

    // Get the index of the start of the line
    String textString = text.toString().substring(0, cursor);
    int lineStartIndex = 0;
    if (textString.contains(mConfig.LINE_SEPARATOR)) {
        lineStartIndex = textString.lastIndexOf(mConfig.LINE_SEPARATOR) + 1;
    }

    // Return whichever is closer before to the cursor
    return Math.max(closestToCursor, lineStartIndex);
}
 
Example #2
Source File: ShareShareInfoHolder.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
private SpannableStringBuilder getSpannerContent(String name, String uid, CharSequence content) {
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String str = "@" + name + ":";
    SpannableString spannableString = new SpannableString(str);
    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#232121")), 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            if (uid != null) {
                UserDetailActivity.start((Activity) widget.getContext(), uid);
            } else {
                ToastUtils.showShortToast("用户数据加载失败");
            }
        }
    }, 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(spannableString).append(content);
    return builder;
}
 
Example #3
Source File: ConfirmIdentityDialog.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public ConfirmIdentityDialog(Context context,
                             MasterSecret masterSecret,
                             MessageRecord messageRecord,
                             IdentityKeyMismatch mismatch)
{
  super(context);
  Recipient       recipient       = RecipientFactory.getRecipientForId(context, mismatch.getRecipientId(), false);
  String          name            = recipient.toShortString();
  String          introduction    = String.format(context.getString(R.string.ConfirmIdentityDialog_the_signature_on_this_key_exchange_is_different), name, name);
  SpannableString spannableString = new SpannableString(introduction + " " +
                                                        context.getString(R.string.ConfirmIdentityDialog_you_may_wish_to_verify_this_contact));

  spannableString.setSpan(new VerifySpan(context, mismatch),
                          introduction.length()+1, spannableString.length(),
                          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

  setTitle(name);
  setMessage(spannableString);

  setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ConfirmIdentityDialog_accept), new AcceptListener(masterSecret, messageRecord, mismatch));
  setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(android.R.string.cancel),               new CancelListener());
}
 
Example #4
Source File: EditableSecureBuffer.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
private boolean removeSpansForChange(int start, int end, boolean textIsRemoved, int i) {
    if(VERBOSE_LOG) Logger.debug(TAG + ": in removeSpansForChange");
    if ((i & 1) != 0) {
        // internal tree node
        if (resolveGap(mSpanMax[i]) >= start &&
                removeSpansForChange(start, end, textIsRemoved, leftChild(i))) {
            return true;
        }
    }
    if (i < mSpanCount) {
        if ((mSpanFlags[i] & Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) ==
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE &&
                mSpanStarts[i] >= start && mSpanStarts[i] < mGapStart + mGapLength &&
                mSpanEnds[i] >= start && mSpanEnds[i] < mGapStart + mGapLength &&
                // The following condition indicates that the span would become empty
                (textIsRemoved || mSpanStarts[i] > start || mSpanEnds[i] < mGapStart)) {
            mIndexOfSpan.remove(mSpans[i]);
            removeSpan(i);
            return true;
        }
        return resolveGap(mSpanStarts[i]) <= end && (i & 1) != 0 &&
                removeSpansForChange(start, end, textIsRemoved, rightChild(i));
    }
    return false;
}
 
Example #5
Source File: HelpsMainAdapter.java    From styT with Apache License 2.0 6 votes vote down vote up
/**
 * 替换表情
 *
 * @param str
 * @param context
 * @return
 */
private SpannableString getSpannableString(String str, Context context) {
    SpannableString spannableString = new SpannableString(str);
    String s = "\\[(.+?)\\]";
    Pattern pattern = Pattern.compile(s, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(spannableString);
    while (matcher.find()) {
        String key = matcher.group();
        int id = Expression.getIdAsName(key);
        if (id != 0) {
            Drawable drawable = context.getResources().getDrawable(id);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            ImageSpan imageSpan = new ImageSpan(drawable);
            spannableString.setSpan(imageSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannableString;
}
 
Example #6
Source File: Selection.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Set the selection anchor to <code>start</code> and the selection edge
 * to <code>stop</code>.
 */
public static void setSelection(Spannable text, int start, int stop) {
    // int len = text.length();
    // start = pin(start, 0, len);  XXX remove unless we really need it
    // stop = pin(stop, 0, len);

    int ostart = getSelectionStart(text);
    int oend = getSelectionEnd(text);

    if (ostart != start || oend != stop) {
        text.setSpan(SELECTION_START, start, start,
                     Spanned.SPAN_POINT_POINT|Spanned.SPAN_INTERMEDIATE);
        text.setSpan(SELECTION_END, stop, stop,
                     Spanned.SPAN_POINT_POINT);
    }
}
 
Example #7
Source File: SignInActivity.java    From monolog-android with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);

    //handler init
    handler=new MyHandler(this);
    mBtnWeixin = (Button) findViewById(R.id.btn_weixin);
    mTvAgreement = (TextView) findViewById(R.id.tv_user_agreement);
    mBtnWeixin.setOnClickListener(this);

    //agreement
    SpannableString agreement = new SpannableString("使用即表示同意用户协议");
    agreement.setSpan(new NoLineClickSpan(), 7, agreement.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    mTvAgreement.setText(agreement);
    mTvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

    //set up umeng
    mLoginController.getConfig().setSsoHandler(new SinaSsoHandler());
    String appId = AppContext.getInstance().getMetaData("WEIXIN_ID");
    String appSecret = AppContext.getInstance().getMetaData("WEIXIN_SECRET");

    // 添加微信平台
    UMWXHandler wxHandler = new UMWXHandler(SignInActivity.this, appId, appSecret);
    wxHandler.addToSocialSDK();
}
 
Example #8
Source File: NewsDisplayActivity.java    From Netease with GNU General Public License v3.0 6 votes vote down vote up
private void updateViewFromJSON(NewRoot newRoot) {
    NewsID hold = newRoot.getNewsID();
    //设置标题
    title.setText(hold.getTitle());

    //设置作者和时间
    int first = hold.getPtime().indexOf("-");
    int last = hold.getPtime().lastIndexOf(":");
    authorAndTime.setText(hold.getSource() + "    " + hold.getPtime().substring(first + 1, last));

    //设置正文
    String body = hold.getBody();
    for (Img img : hold.getImg()) {
        body = body.replace(img.getRef(), template.replace("LINK", img.getSrc()));
    }

    Log.i("RVA", "设置body: " + body);
    URLImageParser p = new URLImageParser(content, this);
    Spanned htmlSpan = Html.fromHtml(body, p, null);
    content.setText(htmlSpan);
    content.setTextSize(18);


}
 
Example #9
Source File: TestSpanMatcher.java    From Markwon with Apache License 2.0 6 votes vote down vote up
public static void textMatches(
        @NonNull Spanned spanned,
        int start,
        int end,
        @NonNull TestSpan.Text text) {

    final String expected = text.literal();
    final String actual = spanned.subSequence(start, end).toString();

    if (!expected.equals(actual)) {
        throw new ComparisonFailure(
                String.format(Locale.US, "Text mismatch at {start: %d, end: %d}", start, end),
                expected,
                actual
        );
    }
}
 
Example #10
Source File: ExoVideoPlaybackControlView.java    From ExoVideoView with Apache License 2.0 6 votes vote down vote up
private CharSequence generateFastForwardOrRewindTxt(long changingTime) {

        long duration = player == null ? 0 : player.getDuration();
        String result = Util.getStringForTime(formatBuilder, formatter, changingTime);
        result = result + "/";
        result = result + Util.getStringForTime(formatBuilder, formatter, duration);

        int index = result.indexOf("/");

        SpannableString spannableString = new SpannableString(result);


        TypedValue typedValue = new TypedValue();
        TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorAccent});
        int color = a.getColor(0, 0);
        a.recycle();
        spannableString.setSpan(new ForegroundColorSpan(color), 0, index, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.WHITE), index, result.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
 
Example #11
Source File: ConverterHtmlToSpanned.java    From memoir with Apache License 2.0 6 votes vote down vote up
private void endHeader() {
    int len = mResult.length();
    Object obj = getLast(Header.class);

    int where = mResult.getSpanStart(obj);

    mResult.removeSpan(obj);

    // Back off not to change only the text, not the blank line.
    while (len > where && mResult.charAt(len - 1) == '\n') {
        len--;
    }

    if (where != len) {
        Header h = (Header) obj;
        mResult.setSpan(new RelativeSizeSpan(HEADER_SIZES[h.mLevel]), where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mResult.setSpan(new BoldSpan(), where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example #12
Source File: DrawableMarginSpan.java    From JotaTextEditor with Apache License 2.0 6 votes vote down vote up
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
                              int top, int baseline, int bottom,
                              CharSequence text, int start, int end,
                              boolean first, Layout layout) {
    int st = ((Spanned) text).getSpanStart(this);
    int ix = (int)x;
    int itop = (int)layout.getLineTop(layout.getLineForOffset(st));

    int dw = mDrawable.getIntrinsicWidth();
    int dh = mDrawable.getIntrinsicHeight();

    if (dir < 0)
        x -= dw;

    // XXX What to do about Paint?
    mDrawable.setBounds(ix, itop, ix+dw, itop+dh);
    mDrawable.draw(c);
}
 
Example #13
Source File: RTLayout.java    From memoir with Apache License 2.0 6 votes vote down vote up
public RTLayout(Spanned spanned) {
    if (spanned != null) {
        String s = spanned.toString();
        int len = s.length();

        // find the line breaks and the according lines / paragraphs
        mNrOfLines = 1;
        Matcher m = LINEBREAK_PATTERN.matcher(s.substring(0, len));
        int groupStart = 0;
        while (m.find()) {
            // the line feeds are part of the paragraph              isFirst          isLast
            Paragraph paragraph = new Paragraph(groupStart, m.end(), mNrOfLines == 1, false);
            mParagraphs.add(paragraph);
            groupStart = m.end();
            mNrOfLines++;
        }

        // even an empty line after the last cr/lf is considered a paragraph
        if (mParagraphs.size() < mNrOfLines) {
            mParagraphs.add(new Paragraph(groupStart, len, mNrOfLines == 1, true));
        }
    }
}
 
Example #14
Source File: LinkableLabel.java    From Tehreer-Android with Apache License 2.0 6 votes vote down vote up
private void refreshActiveLink() {
    Spanned spanned = getSpanned();
    ComposedFrame composedFrame = getComposedFrame();

    if (spanned != null && composedFrame != null && mActiveLinkSpan != null) {
        int spanStart = spanned.getSpanStart(mActiveLinkSpan);
        int spanEnd = spanned.getSpanEnd(mActiveLinkSpan);

        mActiveLinkPath = composedFrame.generateSelectionPath(spanStart, spanEnd);
        mActiveLinkPath.offset(composedFrame.getOriginX(), composedFrame.getOriginY());
    } else {
        mActiveLinkPath = null;
    }

    invalidate();
}
 
Example #15
Source File: StaticKeyMifareReadStep.java    From Walrus with GNU General Public License v3.0 6 votes vote down vote up
public SpannableStringBuilder getDescription(Context context) {
    SpannableStringBuilder builder = new SpannableStringBuilder();

    // TODO XXX: i18n (w/ proper pluralisation)

    MiscUtils.appendAndSetSpan(builder, "Block(s): ",
            new StyleSpan(android.graphics.Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(MiscUtils.unparseIntRanges(blockNumbers));
    builder.append('\n');

    MiscUtils.appendAndSetSpan(builder, "Key: ",
            new StyleSpan(android.graphics.Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(key.toString());
    builder.append('\n');

    MiscUtils.appendAndSetSpan(builder, "Slot(s): ",
            new StyleSpan(android.graphics.Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(
            keySlotAttempts == KeySlotAttempts.BOTH ? context.getString(R.string.both) :
            keySlotAttempts.toString());

    return builder;
}
 
Example #16
Source File: AgentWebX5Utils.java    From AgentWebX5 with Apache License 2.0 6 votes vote down vote up
public static void show(View parent,
                        CharSequence text,
                        int duration,
                        @ColorInt int textColor,
                        @ColorInt int bgColor,
                        CharSequence actionText,
                        @ColorInt int actionTextColor,
                        View.OnClickListener listener) {
    SpannableString spannableString = new SpannableString(text);
    ForegroundColorSpan colorSpan = new ForegroundColorSpan(textColor);
    spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    snackbarWeakReference = new WeakReference<>(Snackbar.make(parent, spannableString, duration));
    Snackbar snackbar = snackbarWeakReference.get();
    View view = snackbar.getView();
    view.setBackgroundColor(bgColor);
    if (actionText != null && actionText.length() > 0 && listener != null) {
        snackbar.setActionTextColor(actionTextColor);
        snackbar.setAction(actionText, listener);
    }
    snackbar.show();

}
 
Example #17
Source File: StickerSetNameCell.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
private void updateUrlSearchSpan() {
    if (url != null) {
        SpannableStringBuilder builder = new SpannableStringBuilder(url);
        try {
            builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameHighlight)), 0, urlSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName)), urlSearchLength, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception ignore) {
        }
        urlTextView.setText(builder);
    }
}
 
Example #18
Source File: SpanUtils.java    From styT with Apache License 2.0 5 votes vote down vote up
public static SpannableString getImageSpan(Context context) {
    SpannableString spannableString = new SpannableString("芭芭拉小魔仙 魔法棒");
    Drawable drawable = context.getResources().getDrawable(R.mipmap.fx);
    drawable.setBounds(0, 0, 70, 70);
    ImageSpan imageSpan = new ImageSpan(drawable);
    spannableString.setSpan(imageSpan, 6, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    return spannableString;
}
 
Example #19
Source File: LicensesActivity.java    From justaline-android with Apache License 2.0 5 votes vote down vote up
private void makeLinkInDescriptionClickable(TextView licenseTypeTextView) {

        String apacheLicenseText = getString(R.string.apache_license_type);
        String apacheUrlText = getString(R.string.apache_license_url);

        // Apache Spannables setup
        SpannableString apacheSpannableString = new SpannableString(apacheLicenseText);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                openUrl(R.string.apache_license_url);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        };
        int apacheStart = apacheLicenseText.indexOf(apacheUrlText);
        apacheSpannableString
                .setSpan(clickableSpan, apacheStart, apacheStart + apacheUrlText.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        licenseTypeTextView.setText(apacheSpannableString);
        licenseTypeTextView.setMovementMethod(LinkMovementMethod.getInstance());
        licenseTypeTextView.setHighlightColor(Color.TRANSPARENT);
    }
 
Example #20
Source File: TextUtils.java    From ResearchStack with Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    for (int i = start; i < end; i++) {
        if (!Character.isLetterOrDigit(source.charAt(i))) {
            return "";
        }
    }
    return null;
}
 
Example #21
Source File: NSDeviceStatus.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
public Spanned getExtendedUploaderStatus() {
    StringBuilder string = new StringBuilder();

    Iterator iter = uploaders.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry pair = (Map.Entry) iter.next();
        Uploader uploader = (Uploader) pair.getValue();
        String device = (String) pair.getKey();
        string.append("<b>").append(device).append(":</b> ").append(uploader.battery).append("%<br>");
    }

    return Html.fromHtml(string.toString());
}
 
Example #22
Source File: CorePlugin.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeSetText(@NonNull TextView textView, @NonNull Spanned markdown) {
    OrderedListItemSpan.measure(textView, markdown);

    // @since 4.4.0
    // we do not break API compatibility, instead we introduce the `instance of` check
    if (markdown instanceof Spannable) {
        final Spannable spannable = (Spannable) markdown;
        TextViewSpan.applyTo(spannable, textView);
    }
}
 
Example #23
Source File: TextLayoutSpan.java    From Markwon with Apache License 2.0 5 votes vote down vote up
/**
 * @see #applyTo(Spannable, Layout)
 */
@Nullable
public static Layout layoutOf(@NonNull CharSequence cs) {
    if (cs instanceof Spanned) {
        return layoutOf((Spanned) cs);
    }
    return null;
}
 
Example #24
Source File: JumpingBeans.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
private static CharSequence removeJumpingBeansSpans(Spanned text) {
    SpannableStringBuilder sbb = new SpannableStringBuilder(text.toString());
    Object[] spans = text.getSpans(0, text.length(), Object.class);
    for (Object span : spans) {
        if (!(span instanceof JumpingBeansSpan)) {
            sbb.setSpan(span, text.getSpanStart(span),
                    text.getSpanEnd(span), text.getSpanFlags(span));
        }
    }
    return sbb;
}
 
Example #25
Source File: VideoMixRecordActivity.java    From PLDroidShortVideo with Apache License 2.0 5 votes vote down vote up
private void showDescription(String filterName, int time) {
    SpannableString description = new SpannableString(String.format("%s%n<<左右滑动切换滤镜>>", filterName));
    description.setSpan(new AbsoluteSizeSpan(30, true), 0, filterName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    description.setSpan(new AbsoluteSizeSpan(14, true), filterName.length(), description.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    mFilterDescription.removeCallbacks(effectDescriptionHide);
    mFilterDescription.setVisibility(View.VISIBLE);
    mFilterDescription.setText(description);
    mFilterDescription.postDelayed(effectDescriptionHide, time);
}
 
Example #26
Source File: Prism4jThemeDefault.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Override
protected void applyColor(
        @NonNull String language,
        @NonNull String type,
        @Nullable String alias,
        @ColorInt int color,
        @NonNull SpannableStringBuilder builder,
        int start,
        int end) {

    if ("css".equals(language) && isOfType("string", type, alias)) {
        super.applyColor(language, type, alias, 0xFF9a6e3a, builder, start, end);
        builder.setSpan(new BackgroundColorSpan(0x80ffffff), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return;
    }

    if (isOfType("namespace", type, alias)) {
        color = applyAlpha(.7F, color);
    }

    super.applyColor(language, type, alias, color, builder, start, end);

    if (isOfType("important", type, alias)
            || isOfType("bold", type, alias)) {
        builder.setSpan(new StrongEmphasisSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (isOfType("italic", type, alias)) {
        builder.setSpan(new EmphasisSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example #27
Source File: LinkTextView.java    From LinkTextView with MIT License 5 votes vote down vote up
/**
 * Remove link by link ID
 *
 * @param linkID
 */
public void removeLink(int linkID) {
    if (!mLinkIDMap.containsKey(linkID)) {
        return;
    }

    try {
        mLinkIDMap.remove(linkID);
    } catch (Exception e) {
        //TODO: Log...
    }

    //Reset all links
    mSpannableString = new SpannableString(mOriginText);
    for (Integer id : mLinkIDMap.keySet()) {
        final LinkTextHolder linkTextHolder = mLinkIDMap.get(id);
        mSpannableString.setSpan(new TouchableSpan(linkTextHolder) {
            @Override
            public void onClick(View view) {
                if (linkTextHolder.mOnClickInLinkText != null) {
                    linkTextHolder.mOnClickInLinkText.onLinkTextClick(linkTextHolder.mText,
                            linkTextHolder.mLinkID, linkTextHolder.mAttachment);
                }
            }
        }, linkTextHolder.mBeginIndex, linkTextHolder.mEndIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    updateLinks();
}
 
Example #28
Source File: Tx3gDecoder.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("ReferenceEquality")
private static void attachFontFamily(SpannableStringBuilder cueText, String fontFamily,
    String defaultFontFamily, int start, int end, int spanPriority) {
  if (fontFamily != defaultFontFamily) {
    cueText.setSpan(new TypefaceSpan(fontFamily), start, end,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | spanPriority);
  }
}
 
Example #29
Source File: ShareCompat.java    From android-recipes-app with Apache License 2.0 5 votes vote down vote up
/**
 * Get the styled HTML text shared with the target activity.
 * If no HTML text was supplied but {@link Intent#EXTRA_TEXT} contained
 * styled text, it will be converted to HTML if possible and returned.
 * If the text provided by {@link Intent#EXTRA_TEXT} was not styled text,
 * it will be escaped by {@link android.text.Html#escapeHtml(CharSequence)}
 * and returned. If no text was provided at all, this method will return null.
 *
 * @return Styled text provided by the sender as HTML.
 */
public String getHtmlText() {
    String result = mIntent.getStringExtra(IntentCompat.EXTRA_HTML_TEXT);
    if (result == null) {
        CharSequence text = getText();
        if (text instanceof Spanned) {
            result = Html.toHtml((Spanned) text);
        } else if (text != null) {
            result = IMPL.escapeHtml(text);
        }
    }
    return result;
}
 
Example #30
Source File: HtmlCompat.java    From HtmlCompat with Apache License 2.0 5 votes vote down vote up
private static void encodeTextAlignmentByDiv(Context context, StringBuilder out, Spanned text, int option) {
    int len = text.length();
    int next;
    for (int i = 0; i < len; i = next) {
        next = text.nextSpanTransition(i, len, ParagraphStyle.class);
        ParagraphStyle[] styles = text.getSpans(i, next, ParagraphStyle.class);
        String elements = " ";
        boolean needDiv = false;
        for (ParagraphStyle style : styles) {
            if (style instanceof AlignmentSpan) {
                Layout.Alignment align =
                        ((AlignmentSpan) style).getAlignment();
                needDiv = true;
                if (align == Layout.Alignment.ALIGN_CENTER) {
                    elements = "align=\"center\" " + elements;
                } else if (align == Layout.Alignment.ALIGN_OPPOSITE) {
                    elements = "align=\"right\" " + elements;
                } else {
                    elements = "align=\"left\" " + elements;
                }
            }
        }
        if (needDiv) {
            out.append("<div ").append(elements).append(">");
        }
        withinDiv(context, out, text, i, next, option);
        if (needDiv) {
            out.append("</div>");
        }
    }
}