設定指定文字的顏色

來源:互聯網
上載者:User

有時候我們經常需要設定指定文字的顏色,比如查詢到的文字設定成和其它不一樣的顏色,高亮顯示,剛剛我試了效果還不錯,特放上來留著筆記,以後直接來copy就可以了,我是個懶蟲,核心代碼如下

//test====================================
這些我是寫在BaseAdapter裡面的getView方法裡的,因這些個資料是在listView中的,所以設了幾個標記
if(isColor && null != strColor && (list.get(position).getContent()).lastIndexOf(strColor)!= -1){
LogWrapper.i("longlong", "test===================");
SpannableString span = new SpannableString(list.get(position).getContent());

span.setSpan(new ForegroundColorSpan(Color.GREEN), 
(list.get(position).getContent()).lastIndexOf(strColor),
(list.get(position).getContent()).lastIndexOf(strColor)+strColor.length(), 
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.content.setText(span);
}
//test=================================================

else{
LogWrapper.i("longlong","test===================else");
holder.content.setText(list.get(position).getContent());
}

//下面這個是從網上得來的,覺得還不錯,也試了下,他的是過濾掉了其它不匹配的字元,覺得有用,收藏如下

TextView tv = (TextView) findViewById(R.id.hello);
SpannableString s = new SpannableString(getResources().getString(R.string.linkify));

Pattern p = Pattern.compile("abc");

Matcher m = p.matcher(s);

while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(s);

//下面這個聽說是前景色彩用的,我還沒試過,覺得有用,先收下了

  1. SpannableStringBuilder style
    =
    new
    SpannableStringBuilder("test Height light");
  2. //參數一:醒目提示[ForegroundColorSpan前景色彩]
  3. //from:高亮開始
  4. //to:高亮結束
  5. style.setSpan(new
    ForegroundColorSpan(color),
    from, to,
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  6. (TextView)view.setText(style);

//下面這些個沒試過,聽說效果更牛,這麼晚了,先不試了,先收了,

可以使用以下兩種方法來實現:
1.用Html類的fromHtml()方法格式化要放到TextView裡的文字。這種方法不僅能夠高亮部分文字,而且還能夠使用HTML裡面方式來格式化文字,顯示出各種效果。

 
  1. TextView.setText(Html.fromHtml("<font color=#FF0000>hello</font>"));

上述代碼把hello設定成紅色。
2.使用Spannable或實現它的類,如SpannableString。Spannable對象也可以實現一樣的效果

  

 
  1. SpannableString ss = new SpannableString("abcdefgh");
  2. ss.setSpan(new BackgroundColorSpan(Color.RED), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  3. TextView.setText(ss);

上述代碼把[2,4)之間的字元設定成紅色,也就是c和d。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.