温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android如何更改TextView中任意位置字体大小和颜色

发布时间:2021-07-23 09:26:16 阅读:172 作者:小新 栏目:移动开发
Android开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇文章将为大家详细讲解有关android如何更改TextView中任意位置字体大小和颜色,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

这里介绍两种方法,一种是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标签的效果:

android如何更改TextView中任意位置字体大小和颜色

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, 01, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
builder.setSpan(whiteSpan, 12, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 
builder.setSpan(blueSpan, 23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
builder.setSpan(greenSpan, 34, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textView.setText(builder);

使用Spannable效果如下图:

android如何更改TextView中任意位置字体大小和颜色

关于“android如何更改TextView中任意位置字体大小和颜色”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×