The following code shows how I'm applying a pressed state using a custom ClickableSpan and selector. However, the pressed state is applied whenever I press anywhere on the TextView, not just the ClickableSpan. How do I stop this?
Note: it does not call onClick
, but does apply state_pressed
from the selector. I want it to do neither.
MyView.java
SpannableString spanned = new SpannableString("click here");
spannable.setSpan(new MyClickableSpan() {
@Override
public void onClick(View widget) {
doSomething();
}
}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanned);
textView.setMovementMethod(LinkMovementMethod.getInstance());
MyClickableSpan.java
public abstract class MyClickableSpan extends ClickableSpan {
@Override
public abstract void onClick(View view);
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}
the TextView
<TextView
android:id="@+id/my_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textColorLink="@color/my_selector" />
my_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/my_color_pressed" />
<item android:color="@color/my_color" />
</selector>
Edit note: Added TextView code
Next example works as you're expecting:
Spannable span = SpannableStringBuilder.valueOf("Hello clickable span!");
span.setSpan(new MyClickableSpan(), 6, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.setText(span);
mTextView.setMovementMethod(LinkMovementMethod.getInstance());
Now span applied:
Here's MyClickableSpan() that's only show Snackbar to indicate that "click" is handled:
class MyClickableSpan extends ClickableSpan {
@Override
public void onClick(View widget) {
Snackbar.make(getWindow().findViewById(android.R.id.content), "Click on span!", Snackbar.LENGTH_LONG).show();
}
}
We've got:
That's it. Please let me know if you need any additional info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With