Android中更改字體顏色的多種方法


在開發中,偶爾要單獨更改TextView中某些字的字體顏色,慢慢摸索出幾種方法,之後有發現會再更新...

1.通過SpannableStringBuilder來實現,它就像html裏邊的元素改變指定文字的文字顏色或背景色

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

原文:http://www.2cto.com/kf/201409/335648.html

2.通過解析HTML代碼的方法實現

 
textView = (TextView) findViewById(R.id.textView);

String string = " 我已閱讀並同意 ";
textView.setText(Html.fromHtml(string));


其實就是單獨設置了font塊的字體顏色,是Html的語法,在setText()中調用Html.fromHtml方法進行解析顯示出來。


若有發現其他方法會再繼續更新~~~

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