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);






  • // 文本样式
  •         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), 0, 7,                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);            sp.setSpan( new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 0, 7,                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  


有两种方法可以定义字符串的不同Style:
  • 第一种方法通过在StringResource中直接定义一些Html标签可以满足一些最基本的设置,比如:设置粗体或者斜体等。目前所支持的标签包括:B(粗体)、I(斜体)、U(下划线)、TT(字符之间的距离)、BIG、SMALL、SUP(上标)、SUB(下标)和STRIKE(删除线)等…
    下边提供一个简单的实例:
1.<resource>
2.    <string>id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
3.</resource>


  • 第二种方法是在.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);