解决SpannableStringBuilder点击事件和字体颜色不生效

String contet= "为了让您更好的使用本软件,请充分阅读并理解《隐私政策》与《使用条款》。";
 tv_content.setText(updateTextStyle(content));

//添加这句话,否则点击不生效 
tv_content.setMovementMethod(LinkMovementMethod.getInstance());

  private SpannableStringBuilder updateTextStyle(String content) {
        SpannableStringBuilder spannableString = new SpannableStringBuilder();
        spannableString.append(content);
    
     //使用ForegroundColorSpan添加点击事件会出现冲突
        UnderlineSpan colorSpan = new UnderlineSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#fe9500"));//设置颜色
            }
        };


       //使用UnderlineSpan很好的兼容这个问题
        UnderlineSpan colorSpan1 = new UnderlineSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#fe9500"));//设置颜色
             //   ds.setUnderlineText(false); //去掉下划线
            }
        };

        int privacyBeginIndex = content.indexOf("《");
        int privacyEndIndex = content.indexOf("》") + 1;
        int protocolBeginIndex = content.lastIndexOf("《");
        int protocolEndIndex = content.lastIndexOf("》") + 1;



        ClickableSpan privacyClickableSpan = new ClickableSpan() {

            @Override
            public void onClick(@NonNull View widget) {
                Toast.makeText(MainActivity.this, "123", Toast.LENGTH_LONG).show();

            }
        };

        ClickableSpan protocolClickableSpan = new ClickableSpan() {

            @Override
            public void onClick(@NonNull View widget) {
                 Toast.makeText(MainActivity.this, "123", Toast.LENGTH_LONG).show();
           
            }
        };

        spannableString.setSpan(protocolClickableSpan, protocolBeginIndex, protocolEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableString.setSpan(privacyClickableSpan, privacyBeginIndex, privacyEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //字体颜色一定要放在点击事件后面,不然部分手机不会修改颜色
        spannableString.setSpan(colorSpan, protocolBeginIndex, protocolEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableString.setSpan(colorSpan1, privacyBeginIndex, privacyEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);


        return spannableString;
    }

你可能感兴趣的:(解决SpannableStringBuilder点击事件和字体颜色不生效)