博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android TextView 设置部分文字背景色 和 文字颜色
阅读量:7282 次
发布时间:2019-06-30

本文共 1753 字,大约阅读时间需要 5 分钟。

通过SpannableStringBuilder来实现,它就像html里边的元素改变指定文字的文字颜色或背景色

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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://sykjm.baihongyu.com/

你可能感兴趣的文章
如何评估你的创业点子
查看>>
阿里云的下一个十年,云计算驱动制造业
查看>>
关于MongoDB Sharding,你应该知道的
查看>>
Git基础06:介绍一个成功的 Git 分支模型
查看>>
[MySQL源码] Innodb如何处理auto_inc值
查看>>
Git(进击学习:远程仓库操作)-V3.0
查看>>
mysql常用基础操作语法(九)~~外连接查询【命令行模式】
查看>>
lamp lnmp lnamp区别
查看>>
Shell 历史记录异地留痕审计与监控
查看>>
机器学习理论研究方法探讨
查看>>
日志服务(原SLS)新功能发布(15)--控制台支持查看协同消费组(ConsumerGroup)消费进度...
查看>>
深入Protobuf源码-概述、使用以及代码生成实现
查看>>
双网卡同时上网
查看>>
LVM学习之逻辑卷及卷组缩小空间
查看>>
NHibernate 2 学习
查看>>
iOS中大流中的自定义cell 技术分享
查看>>
SGA Heap size 2098K exceeds notification threshold (2048K)的问题
查看>>
ListView 适配器实现getviewtypecount() 数组越界IndexOutOfBoundException
查看>>
“插入排序”算法Java语言的实现与详解
查看>>
《Netty 权威指南》—— AIO版本时间服务器运行结果
查看>>