這里介紹兩種方法,一種是Spannable,一種是Html.fromHtml(通過html標簽來改變),實際中看您使用哪種方便選擇使用即可
1.Html.fromHtml的使用
TextView textView = (TextView) findViewById(R.id.text);String textSource = "修改TextView中部分文字的<font color='#ff0000'><big>大</big><small>小</small></font>和<font color='#00ff00'>顏色</font>,展示多彩效果!";textView.setText(Html.fromHtml(textSource));
上面是沒有加html標簽,下面是加了html標簽的效果:

2.使用Spannable來實現
textView = (TextView) findViewById(R.id.textview); SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString()); //ForegroundColorSpan 為文字前景色,BackgroundColorSpan為文字背景色 ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED); ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE); ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE); ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW); builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE); builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(builder);
使用Spannable效果如下圖:

是不是很簡單,但是效果強大,趕緊來實現吧!!!
以上這篇android 更改TextView中任意位置字體大小和顏色的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答