android 更改TextView中任意位置字型大小和顏色
阿新 • • 發佈:2019-02-05
這裡介紹兩種方法,一種是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效果如下圖:
是不是很簡單,但是效果強大,趕緊來實現吧!!!