给TextView控件内容每一个文字设置点击事件

String dst = "Liver and kidney are particularly rich in vitamin A.";
        SpannableStringBuilder ssInfo = new SpannableStringBuilder(dst);
        String[] split = dst.split(" ");
        for (String subContent: split){
            Pattern pattern = Pattern.compile(subContent);
            Matcher matcher = pattern.matcher(dst);
            while (matcher.find()){
                final String group = matcher.group();
                ClickableSpan cs = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        Log.e("zqh","group = "+group);
                        DialogUtil.showToast(group);
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                    //去掉富文本可点击文字的下滑线等样式
                        ds.setUnderlineText(false);
//                        super.updateDrawState(ds);
                    }
                };
                ssInfo.setSpan(cs,matcher.start(),matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        translateTextView.setText(ssInfo);//设置给textview
        //设置光标起始位置计算方式
        translateTextView.setMovementMethod(LinkMovementMethod.getInstance());

 

你可能感兴趣的:(Android)