1. 程式人生 > >TextView控制元件之部分文字內容設定前景、背景色等

TextView控制元件之部分文字內容設定前景、背景色等

ForegroundColorSpan 設定前景色

BackgroundColorSpan 設定背景色

ClickSpan 點選效果實現

新增下劃線

StrikethroughSpan 設定刪除線

String content = "花兒是紅色的,樹葉是綠色的。";
SpannableStringBuilder  builder = new SpannableStringBuilder(content);

//前景色
int foreColor = Color.RED;
ForegroundColorSpan colorSpan = new ForegroundColorSpan(foreColor);
builder.setSpan(colorSpan, 3
, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); textView.setText(buidler);

執行結果為:花兒是紅色的,樹葉是綠色的。

String content = "花兒是紅色的,樹葉是綠色的。";
SpannableStringBuilder  builder = new SpannableStringBuilder(content);
//背景色
int bgColor = Color.GREEN;
BackgroundColorSpan colorSpan = new BackgroundColorSpan (bgColor );
builder.setSpan(colorSpan, 10
, 12, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); textView.setText(buidler);

執行結果為:花兒是紅色的,樹葉是綠色的。

String content = "花兒是紅色的,樹葉是綠色的。";
SpannableStringBuilder  builder = new SpannableStringBuilder(content);
int start = 3;
int end = 5;
 ClickableSpan clickSpan = new ClickableSpan() {
            @Override
            public
void onClick(View widget) { //點選後的操作 listener.onClickText(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); //去掉下劃線,預設會帶有下劃線 ds.setUnderlineText(false); //設定點選文字的顏色 ds.setColor(Color.RED)); } }; builder .setSpan(clickSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); textView.setText(builder); //此句必不可少 textView.setMovementMethod(LinkMovementMethod.getInstance());

執行結果為:花兒是紅色的,樹葉是綠色的。

如果是在資原始檔裡,可以這樣寫.
< resources >   
    < string name = "url" > <u>http://www.baidu.com</u> </ string >   
</ resources > 

如果是程式碼這樣寫
    TextView textView = (TextView)findViewById(R.id.text);   
    textView.setText(Html.fromHtml("<u>" + "http://www.baidu.com" + "</u>" ));
String content = "花兒是紅色的,樹葉是綠色的。";
SpannableStringBuilder  builder = new SpannableStringBuilder(content);
int start = 3;
int end = 5;
StrikethroughSpan stSpan = new StrikethroughSpan();
builder.setSpan(stSpan, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(builder);

執行結果為:花兒是紅色的,樹葉是綠色的。

注:如果是給所有文字新增這些效果,可參考文字控制元件的屬性設定。