android 中TextView设置部分文字背景色和文字颜色
通過SpannableStringBuilder來實現,它就像html里邊的元素改變指定文字的文字顏色或背景色
public class MainActivity extends Activity {@Overrideprotected 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);}}
項目中代碼:
//textview 設置部分顏色public SpannableStringBuilder setPartColorText(String str){//使用SpannableStringBuilder類SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder(str);//確定部分顏色的位置int start=str.indexOf(content);int end=start+content.length();//確定顏色為紅色ForegroundColorSpan mForeColor=new ForegroundColorSpan(Color.RED);//setspanspannableStringBuilder.setSpan(mForeColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);return spannableStringBuilder;}
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----如果設置了此風格,會有一條線從中間穿過所有的字,就像被劃掉一樣
總結
以上是生活随笔為你收集整理的android 中TextView设置部分文字背景色和文字颜色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java设计模式-命令模式Command
- 下一篇: Android真机调试打印日志的方法