2025年3月24日 星期一 甲辰(龙)年 月廿三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > 安卓(android)开发

android 通用文本控件设置可点击/多颜色(带跳转事件)的ClickableSpan

时间:02-13来源:作者:点击数:56

1.介绍 例:对一个TextView设置一段文字内容,可对内容中部分文字设置不同颜色,并设置对应点击事件。

项目中常见用处:初次使用app是弹出的用户使用协议中,其中《用户协议》《隐私政策》 这些文字内容可能需要设置为不同颜色 并且可以点击跳转到对应的内容界面。

  • /**
  • * 文本ClickableSpan
  • */
  • public class CommonClickableSpan extends ClickableSpan {
  • Context context;
  • int colorId;
  • Class startActivity;
  • private Bundle bundle;
  • private HashMap<String,Object> paramMap=new HashMap<>();
  • public CommonClickableSpan(@NonNull Context context, int colorId, @NonNull Class startActivity, Bundle bundle){
  • this.context=context;
  • this.colorId=colorId;//可点击的文本颜色
  • this.startActivity=startActivity;//点击文本跳转的界面
  • this.bundle=bundle;//包含传递参数的bundle
  • }
  • public CommonClickableSpan(@NonNull Context context, int colorId, @NonNull Class startActivity){
  • this.context=context;
  • this.colorId=colorId;//可点击的文本颜色
  • this.startActivity=startActivity;//点击文本跳转的界面
  • }
  • @Override
  • public void updateDrawState(TextPaint ds) {
  • ds.setColor(colorId);
  • }
  • @Override
  • public void onClick(View widget) {
  • Intent intent=new Intent(context,startActivity);
  • if (bundle!=null){
  • intent.putExtras(bundle);
  • }
  • context.startActivity(intent);
  • }
  • }

2.使用

  • String str1="1.购买会员成功。享用的会员时间为:永久会员天数不限制,一季度为90天,半年为180天,一年为365天;\n";
  • String str2="2.会员服务开通后不支持退款。更多详情条款,请查看";
  • String str3="《会员服务协议》";
  • SpannableStringBuilder span = new SpannableStringBuilder(str1+str2+str3);
  • Bundle bundle=new Bundle();
  • bundle.putString(Constant.KEY_TITLE,"会员服务协议");
  • bundle.putString(Constant.WEB_URL,"协议链接地址");
  • span.setSpan(
  • new CommonClickableSpan(this, ContextCompat.getColor(this,R.color.color_73b9ff), WebActivity.class,bundle),
  • (str1+str2).length(),
  • (str1+str2+str3).length() ,
  • Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  • vip_explain_tv.setText(span);
  • vip_explain_tv.setMovementMethod(LinkMovementMethod.getInstance());//TextView凡是点击能跳转时此代码必须设置
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门