您的位置:首页 > 其它

textView文本不同颜色

2010-06-04 17:44 302 查看
// 文本样式
EditText et = (EditText) findViewById(R.id.tv);
et.setText("Styling the content of an editText dynamically");
Spannable sp = et.getText();
sp.setSpan(new BackgroundColorSpan(Color.RED), 3, 8,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //3代表从第几个字符开始变颜色,注意第一个字符序号是0.
//8代表变色到第几个字符.

sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 0, 7,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(sp);  

java程序中动态改变TextView特定内容的Style或者实现更为复杂的效果,下边将使用Spannable介绍具体的实现方法,请参照以下代码设置:
01.// Get our EditText object.
02.EditText vw = (EditText)findViewById(R.id.text);
03.

04.// Set the EditText's text.
05.vw.setText("Italic, highlighted, bold.");
06.

07.// If this were just a TextView, we could do:
08.// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
09.// to force it to use Spannable storage so styles can be attached.
10.// Or we could specify that in the XML.
11.

12.// Get the EditText's internal text storage
13.Spannable str = vw.getText();
14.

15.// Create our span sections, and assign a format to each.
16.str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
17.str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
18.str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

和大家分享一下:
TextView tv;
tv.setText("Test");
Spannable span = (Spannable)tv.getText();
spn.setSpan(new BackgroundColor(#ffffffff), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ps:start和end表示你要高亮显示的子串在Test中的起始和结束位置。
go2android 发表于 2009-9-11 10:19

忘了一项,setText的时候要用setText("Text", TextView.BufferType.SPANNABLE);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: