Android TextView ClickableSpan 分段点击实现

最新项目遇到TextView分段点击的问题,类似新浪微博@多个人的点击效果,效果图如下:
这里写图片描述

这里写图片描述

具体主要通过CustomClickableSpan类来实现,CustomClickableSpan继承自ClickableSpan,在构造方法传入子串的开始位置。

Activity类:
public class ClickableSpanActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clickable_span);

    TextView tvContent = (TextView) findViewById(R.id.TextView_Content);

    String content = "@阿里巴巴 @百度 @腾讯 真有钱!";

    layoutContent(tvContent, content);
}

private void layoutContent(TextView textView, String content) {
    if (!content.contains("@")) {
        textView.setText(content);
        return;
    }

    SpannableStringBuilder builder = new SpannableStringBuilder(content);

    int index = 0;
    while (content.indexOf("@", index) != -1) {
        int atIndex = content.indexOf("@", index);  //@的位置
        int sIndex = content.indexOf(" ", atIndex); //空格的位置

        index = sIndex;
        if (sIndex < atIndex) { //格式不符合
            continue;
        }
        Log.d("ClickSpan", "@ = " + atIndex + " S = " + sIndex);

        CustomClickableSpan clickableSpan = new CustomClickableSpan(this, atIndex);
        builder.setSpan(clickableSpan, atIndex, sIndex, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(builder);
}

}

CustomClickableSpan类:
public class CustomClickableSpan extends ClickableSpan {

private Context mContext;
private int mAtIndex;

public CustomClickableSpan(Context context, int atIndex) {
    mContext = context;
    mAtIndex = atIndex;
}

@Override
public void onClick(View widget) {
    if (widget instanceof TextView) {
        TextView textView = (TextView) widget;
        Log.d("SpanContent", "Content = " + textView.getText().toString());

        String str = textView.getText().toString();
        int sIndex = str.indexOf(" ", mAtIndex);
        Toast.makeText(mContext, str.substring(mAtIndex + 1, sIndex), Toast.LENGTH_SHORT).show();
    }
}

@Override
public void updateDrawState(TextPaint ds) {
    super.updateDrawState(ds);
    ds.setColor(Color.BLUE);
    ds.setUnderlineText(false);
    ds.clearShadowLayer();
}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值