Android ClickableSpan not calling onClick

前端 未结 4 1415
有刺的猬
有刺的猬 2020-11-30 18:58

I am creating a ClickableSpan, and it is displaying properly with the proper text underlined. However, the clicks are not registering. Do you know what I am doing wrong???

4条回答
  •  北海茫月
    2020-11-30 19:40

    After some trial and error, the sequence of setting the tv.setMovementMethod(LinkMovementMethod.getInstance()); does matter.

    Here's my full code

    String stringTerms = getString(R.string.sign_up_terms);
    Spannable spannable = new SpannableString(stringTerms);
    int indexTermsStart = stringTerms.indexOf("Terms");
    int indexTermsEnd = indexTermsStart + 18;
    spannable.setSpan(new UnderlineSpan(), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Log.d(TAG, "TODO onClick.. Terms and Condition");
        }
    }, indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    int indexPolicyStart = stringTerms.indexOf("Privacy");
    int indexPolicyEnd = indexPolicyStart + 14;
    spannable.setSpan(new UnderlineSpan(), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Log.d(TAG, "TODO onClick.. Privacy Policy");
        }
    }, indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    TextView textViewTerms = (TextView) findViewById(R.id.sign_up_terms_text);
    textViewTerms.setText(spannable);
    textViewTerms.setClickable(true);
    textViewTerms.setMovementMethod(LinkMovementMethod.getInstance());
    

提交回复
热议问题