安卓TextView部分字體改變顏色以及背景

> 1. 第一種使用SpannableStringBuilder和 BackgroundColorSpan

//首先給賦值顏色
ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.text_red));
ForegroundColorSpan graySpan = new ForegroundColorSpan(getResources().getColor(R.color.text_gray));
mTextView.setText(“灰色紅色”);
//這裏注意一定要先給textview賦值
SpannableStringBuilder builder = new SpannableStringBuilder(mTextView.getText().toString());
//爲不同位置字符串設置不同顏色
//四個參數分別爲,顏色值,起始位置,結束位置,最後的爲類型。
builder.setSpan(graySpan, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(redSpan, 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//最後爲textview賦值
mTextView.setText(builder);

 String str="設置TextView部分字體顏色以及背景顏色!";
        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);


補充:
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----如果設置了此風格,會有一條線從中間穿過所有的字,就像被劃掉一樣

> 1. 第二種使用使用Html.fromHtml()

TextView tv= (TextView)findViewById(R.id.desc1);
String content = "更改部分字體<font color='red'>的字體顏色</font>使用Html<font color='red'>或者SpannableStringBuilder</font>!";
tv.setText(Html.fromHtml(content));

參考:http://www.2cto.com/kf/201409/335648.html

http://www.cnblogs.com/kingsam/p/5643598.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章