簡體   English   中英

如何為api level 11構造android AttributedString

[英]How to construct android AttributedString for api level 11

我知道如何在iOS中這樣做,但還沒有在android中 我如何在android中構造一個屬性字符串,其中一部分是粗體的

“這是一個大膽部分的例子”

FWIW,我從未見過使用AttributedString ,在~6。5年的Android開發工作中。

實現Spanned的類包含標記規則(“spans”)。 動態構造一個的最簡單方法是使用Html.fromHtml()來解析帶有<b>等基本標簽的HTML字符串。 字符串資源(例如, res/values/strings.xml )也支持<b><i><u>標記。

或者,您可以自己應用跨度。 在下面的示例代碼中,我從TextView獲取CharSequence ,刪除所有現有的跨度,並使用BackgroundColorSpan突出顯示搜索項:

  private void searchFor(String text) {
    TextView prose=(TextView)findViewById(R.id.prose);
    Spannable raw=new SpannableString(prose.getText());
    BackgroundColorSpan[] spans=raw.getSpans(0,
                                             raw.length(),
                                             BackgroundColorSpan.class);

    for (BackgroundColorSpan span : spans) {
      raw.removeSpan(span);
    }

    int index=TextUtils.indexOf(raw, text);

    while (index >= 0) {
      raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
          + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      index=TextUtils.indexOf(raw, text, index + text.length());
    }

    prose.setText(raw);
  }

(來自這個示例項目

對於粗體或斜體,您可以使用StyleSpan而不是BackgroundColorSpan ,依此類推。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM