同一TextView中字符串的字体大小和颜色不同

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同一TextView中字符串的字体大小和颜色不同相关的知识,希望对你有一定的参考价值。

是否可以在同一文本视图中更改字符串的字体大小和颜色。

例如 :

 _______________
|_______________| --> this is my text view 

我想做的事

________________
|ABC (red color) |
|abc(whitecolor) |
|________________|

字符串应该看起来像这样的“ABC nabc”

答案

使用SpannableStringBuilder

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.WHITE), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

以上是关于同一TextView中字符串的字体大小和颜色不同的主要内容,如果未能解决你的问题,请参考以下文章

如何设置TextView里面字体的大小

给TextView加上多彩效果:改变部分字体的大小和颜色

Android TextView设置部分字体的颜色和大小+Html

TextView字体大小及颜色设置

微信小程序text控件部分字体文字大小和颜色设置四

[Android开发]富文本TextView修改部分字体颜色大小加粗斜体下划线删除线,以及添加点击事件,插入本地或网络图片