經過SpannableStringBuilder來實現,它就像html裏邊的元素改變指定文字的文字顏色或背景色html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public
class
MainActivity
extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str=
"這是設置TextView部分文字背景顏色和前景顏色的demo!"
;
int
bstart=str.indexOf(
"背景"
);
int
bend=bstart+
"背景"
.length();
int
fstart=str.indexOf(
"前景"
);
int
fend=fstart+
"前景"
.length();
SpannableStringBuilder style=
new
SpannableStringBuilder(str);
style.setSpan(
new
BackgroundColorSpan(Color.RED),bstart,bend,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(
new
ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
TextView tvColor=(TextView) findViewById(R.id.tv_color);
tvColor.setText(style);
}
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return
true
;
}
}
|
AbsoluteSizeSpan(int size) ---- 設置字體大小,參數是絕對數值,至關於Word中的字體大小RelativeSizeSpan(float proportion) ---- 設置字體大小,參數是相對於默認字體大小的倍數,好比默認字體大小是x, 那麼設置後的字體大小就是x*proportion,這個用起來比較靈活,proportion>1就是放大(zoom in), proportion<1就是縮小(zoom out)
ScaleXSpan(float proportion) ---- 縮放字體,與上面的相似,默認爲1,設置後就是原來的乘以proportion,大於1時放大(zoon in),小於時縮小(zoom out)BackgroundColorSpan(int color) ----背景着色,參數是顏色數值,能夠直接使用android.graphics.Color裏面定義的常量,或是用Color.rgb(int, int, int)ForegroundColorSpan(int color) ----前景着色,也就是字的着色,參數與背景着色一致TypefaceSpan(String family) ----字體,參數是字體的名字好比「sans", "sans-serif"等StyleSpan(Typeface style) -----字體風格,好比粗體,斜體,參數是android.graphics.Typeface裏面定義的常量,如Typeface.BOLD,Typeface.ITALIC等等。StrikethroughSpan----若是設置了此風格,會有一條線從中間穿過全部的字,就像被劃掉同樣java