Android ClickableSpan不能调用onClick

我正在创build一个ClickableSpan,它正确显示正确的文本下划线。 但是点击没有注册。 你知道我在做什么错? 谢谢,维克多这是代码片段:

view.setText("This is a test"); ClickableSpan span = new ClickableSpan() { @Override public void onClick(View widget) { log("Clicked"); } }; view.getText().setSpan(span, 0, view.getText().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

您是否尝试过在包含span的TextView上设置MovementMethod? 你需要这样做点击工作…

 tv.setMovementMethod(LinkMovementMethod.getInstance()); 

经过一些试验和错误,设置tv.setMovementMethod(LinkMovementMethod.getInstance());的顺序tv.setMovementMethod(LinkMovementMethod.getInstance()); 确实很重要。

这是我的完整代码

 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()); 
Interesting Posts