首页

源码搜藏网

首页 > 安卓源码 > 技术博客 >

使用SpannableStringBuilder打造超炫酷的TextView

创建时间:2017-01-04 08:30  浏览

前段时间项目中使用到了一种效果是更改textview中制定字符串的颜色.于是就查找了下资料,发现了使用SpannableStringBuilder可以很轻易的就实现,并不用使用自定义View.那么就直接先来个代码练练手,运行看下效果.

1
2
3
4
5
String content = "NO ZUO NO DIE!";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#009688"));
spannableStringBuilder.setSpan(colorSpan,3,6, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
mTextView.setText(spannableStringBuilder);

 

运行完了之后肯定会有些疑惑,最主要的SpannableStringBuilder是什么鬼? ForegroundColorSpan又是什么? Spanned.SPAN_EXCLUSIVE_INCLUSIVE 是什么意思? 那么我们来一个一个的解释.

1
2
3
4
void setSpan (Object what,  //设置的样式,看完下面的就明白了.
             int start,   //开始的位置. 索引是从0开始的.
             int end,   //样式结束的位置,不包括end
             int flags) // 样式的标志. 下面详细介绍

flags:

SpannableStringBuilder是什么鬼?

官方文档是这样写的. This is the class for text whose content and markup can both be changed.
很简单,主要作用就是给文本内容添加样式的.主要通过setSpan方法设置样式.就像上面程序中那样. setSpan方法的三个参数是什么意思呢

ForegroundColorSpan 是什么?

根据它的意思就可以猜到,他是用来改变前景色的(也就是文本颜色).有文本颜色那是不是也有背景颜色等其他的呢?那是肯定的啦.只改变个文本颜色岂不是太low了呀.
那么都是主要的都是有哪些呢?
使用SpannableStringBuilder打造超炫酷的TextView

这个类里面的之类都是可以的. 点我查看,无需翻墙
这些类跟ForegroundColorSpan都是大同小异的.掌握了一个,其他的也就掌握了.
我认为常用的是ImageSpan,ClickableSpan,ForegroundColorSpan

再来几个代码练练

再来个ImageSpanForegroundColorSpan混合的的看下效果.

1
2
3
4
5
6
7
String content = "NO ZUO NO DIE!";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#009688"));
spannableStringBuilder.setSpan(colorSpan,3,6, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
ImageSpan imageSpan = new ImageSpan(this,R.mipmap.ic_launcher);
spannableStringBuilder.setSpan(imageSpan,2,3,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
mTextView.setText(spannableStringBuilder);

 

最后来张效果图:

使用SpannableStringBuilder打造超炫酷的TextView

上一篇:Android 6.0之后的动态权限
下一篇:Android基础知识之 Toolbar 的使用

相关内容

热门推荐