使用SpannableString,ClickableSpan,文字部分可点击

最近4个月都在忙一个项目,最近项目接近尾声,所有打算趁这个机会稍微做一点总结。

本次总结的功能是实现一段文字,部分文字颜色不同,部分文字有下划线并且可以点击,主要的思路就是使用SpannableString,自定义一个ClickableSpan。以下就是实现该功能的具体步骤以及相关代码。

1.自定义ClickableSpan,通过不同的type去判断文字显示的颜色以及下划线显示状况。

public abstract class ClickableColorSpan extends ClickableSpan {

		private int type;

		public ClickableColorSpan(int type) {
			// this.str = str;
			this.type = type;
		}

		@Override
		public void updateDrawState(TextPaint ds) {
			if (type == Constants.NOTHING)// 空格情况
			{
				// ds.setColor(ds.linkColor);
				ds.setColor(getActivity().getResources().getColor(
						R.color.linkcolor));
				ds.setUnderlineText(false);//是否显示下划线
			}
			if (type == Constants.DESCRIPTION)// 解释或空格选择
			{
				ds.setColor(getActivity().getResources().getColor(
						R.color.orange));
				ds.setUnderlineText(false);
			}
			if (type == Constants.NORMAL)// 正常情况
			{
				// ds.setColor(ds.linkColor);
				ds.setColor(getActivity().getResources().getColor(
						R.color.linkcolor));
				ds.setUnderlineText(true);
			}
			if (type == Constants.SELECTED)// 非空格选择
			{
				// ds.setColor(ds.linkColor);
				ds.setColor(getActivity().getResources().getColor(
						R.color.orange));
				ds.setUnderlineText(true);
			}
		}
	}

 2.生成富文本 

private SpannableString getClickableSpan() {
		int start = 2;//设置点击范围
		int end = 4;
		SpannableString spanableInfo = new SpannableString("hello word");
		spanableInfo.setSpan(
				new ClickableColorSpan(0) {
					@Override
					public void onClick(View v) {
					//点击事件
					}
				}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		return spanableInfo;
	}
3.给控件赋值

txtView.setText(getClickableSpan());
txtView.setMovementMethod(LinkMovementMethod.getInstance());


  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值