TextView中部分字符串设置点击

在实际开发中,我们经常设置应用的 应用条款和隐私条款为可点击,不同颜色,没有下划线。这种情况一般要借助SpannableString类,下面是实现源码:

SpannableString spanStr = new SpannableString(registerServiceClause.getText().toString());
NoUnderlineSpan underlineSpan = new NoUnderlineSpan();
spanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_de1d1d)), spanStr.length() - 6, spanStr.length() - 2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
spanStr.setSpan(new ClickableSpan() {
    @Override
    public void onClick(View widget) {
        Toast.makeText(getApplicationContext(), "点击", Toast.LENGTH_SHORT).show();
    }
}, spanStr.length() - 6, spanStr.length() - 2, Spanned.SPAN_MARK_MARK);
spanStr.setSpan(underlineSpan, spanStr.length() - 6, spanStr.length() - 2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
registerServiceClause.setText(spanStr);
registerServiceClause.setMovementMethod(LinkMovementMethod.getInstance());

public class NoUnderlineSpan extends UnderlineSpan {
    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setColor(ds.linkColor);
        ds.setUnderlineText(false);
    }
}

SpannableString 直译是可扫描的字符串,

setSpan方法有几个参数,源码:

public void setSpan(Object what, int start, int end, int flags) {
    super.setSpan(what, start, end, flags);
}
  • what  是要发生什么
  • start 起始位置
  • end 结束位置
  • flags 标识

本人讨论群正在招募中:欢迎加入,一起讨论相关技术 QQ群:195109527

 

 

 

 

你可能感兴趣的:(Android)