2014-10-04 111 views

回答

1

FWIW,我从来没有见过使用AttributedString,在〜6.5岁Android开发工作。

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

或者,您可以自己申请跨度。在下面的示例代码中,我得到的CharSequenceTextView,删除所有现有的跨度,并突出显示搜索词与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,等等。

相关问题