android - 如何为 api 级别 11 构建 android AttributedString

标签 android string android-layout

我知道如何在 iOS 中执行此操作,但还不知道 android .如何在 android 中构造一个属性字符串,其中一部分是粗体,如

“这是带有粗体部分的示例”

最佳答案

FWIW,我从未见过AttributedString在大约 6.5 年的 Android 开发工作中使用过。

类实现 Spanned包含标记规则(“跨度”)。动态构造一个的最简单方法是使用 Html.fromHtml()解析带有 <b> 等基本标签的 HTML 字符串.字符串资源(例如 res/values/strings.xml )也支持 <b> , <i> , 和 <u>标签。

或者,您可以自己应用 span。在下面的示例代码中,我得到了 CharSequence来自TextView ,删除所有现有跨度,并使用 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);
  }

(来自 this sample project)

对于粗体或斜体,您可以使用 StyleSpan而不是 BackgroundColorSpan , 等等。

关于android - 如何为 api 级别 11 构建 android AttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26197395/

相关文章:

java - 二维码扫描如何使结果Url可点击?

android - 什么是使用 Messenger 或 Intent 进行更快的交流?

android - 在 Android Media Player 中重播音乐的问题

java - 尝试运行 Google Search Api 时出现 StringIndexOutofBoundsException

regex - PowerShell:输出正则表达式而不是结果

java - Android 工具栏不显示图标和标题

android - javah : Error: cannot access android. support.v7.app.AppCompatActivity?

c - 使用 dup2 重定向时出现空白字符串

android - 如何自定义选项卡操作栏

android - 编辑不接受数字的文本,只接受字母(未设置输入类型)