String字符串,这个咱们经常用,一定很熟悉,而这个SpanableString这个就不常用了,其实它们都可以表示字符串,只不过后者可以轻松地利用官方提供的Api对字符串进行各种风格的设置。
这点需求虽说实现起来不是什么难事,不过选择一个好的方案,可以事半功倍。接下来介绍今天的主角:SpannableString
先看看官方怎么定义这个类的
This is the class for text whose content is immutable but to which markup objects can be attached and detached. For mutable text, see SpannableStringBuilder.
大体意思是:这是文本的类,该文本的内容是不可变的,但可以附加和分离标记对象。对于可变文本,请参见SpannableStringBuilder。
这个类源码很少,100行代码都不到,感兴趣的可以去看看。其中有一个核心方法:setSpan(what,start,end,flags)共有4个参数
常用的Span类有:
flags共有四种属性:
TextView txtInfo = findViewById(R.id.textView);
SpannableString span = new SpannableString("设置前背景色");
span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),3, 5, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
txtInfo.setMovementMethod(LinkMovementMethod.getInstance());
txtInfo.setHighlightColor(getResources().getColor(android.R.color.transparent));
txtInfo.setText(span);
TextView tv8 = findViewById(R.id.tv8);
SpannableString spanStr8 = new SpannableString("文字里添加表情(表情)");
Drawable image = getResources().getDrawable(R.mipmap.ic_launcher);
image.setBounds(new Rect(0,0,50,50));
spanStr8.setSpan(new ImageSpan(image),5, 7,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
tv8.setText(spanStr8);
SpannableString spanStr10 = new SpannableString("请准守协议《XXXXXX协议》");
spanStr10.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
//点击事件
Toast.makeText(MainActivity.this,"点击了我,可以写跳转逻辑",Toast.LENGTH_SHORT).show();
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.parseColor("#ff4d40"));
}
},5,spanStr10.length(),Spanned.SPAN_INCLUSIVE_INCLUSIVE);
tv10.setMovementMethod(LinkMovementMethod.getInstance()); // 必须的设置这个,不然点击效果 不生效
tv10.setHighlightColor(Color.parseColor("#ffffff")); //点击后显示的背景色,我这里设置了白色,默认颜色不好看
tv10.setText(spanStr10);
还有其它一些常规用法,我就不一一列举了,上图:
github地址:https://github.com/A-How/SpanableStringDemo/tree/master
定义字符串用String,对于大量字符串进行拼接,我们可以使用StringBuilder进行处理;SpanableStringBuilder也是对大量SpanableString拼接进行处理的,也同样使用append方法。举个例子:
代码实现
String beforeText = "快快下单";
String afterText = "(立享200元优惠)";
int beforeSize = 20;
int afterSize = 15;
SpannableStringBuilder builder = new SpannableStringBuilder(beforeText);
builder.setSpan(new ForegroundColorSpan(Color.parseColor("#ffdf40")),0,beforeText.length(),Spanned.SPAN_INCLUSIVE_INCLUSIVE);
builder.setSpan(new AbsoluteSizeSpan(beforeSize,true),0,beforeText.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
builder.append(afterText);
builder.setSpan(new ForegroundColorSpan(Color.parseColor("#ff6940")),beforeText.length(),builder.length(),Spanned.SPAN_INCLUSIVE_INCLUSIVE);
builder.setSpan(new AbsoluteSizeSpan(afterSize,true),beforeText.length(),builder.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv12.setText(builder);
后续我会继续添加一些关于SpanableString一些Span类的用法,
github地址:https://github.com/A-How/SpanableStringDemo/tree/master