I have a TextView with multiple ClickableSpans in it. When a ClickableSpan is pressed, I want it to change the color of its text.
I have tried setting a color state
All these solutions are too much work.
Just set android:textColorLink
in your TextView
to some selector. Then create a clickableSpan with no need to override updateDrawState(...). All done.
here a quick example:
In your strings.xml
have a declared string like this:
This is my message%1$s these words are highlighted%2$s and awesome.
then in your activity:
private void createMySpan(){
final String token = "#";
String myString = getString(R.string.mystring,token,token);
int start = myString.toString().indexOf(token);
//we do -1 since we are about to remove the tokens afterwards so it shifts
int finish = myString.toString().indexOf(token, start+1)-1;
myString = myString.replaceAll(token, "");
//create your spannable
final SpannableString spannable = new SpannableString(myString);
final ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(final View view) {
doSomethingOnClick();
}
};
spannable.setSpan(clickableSpan, start, finish, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.setMovementMethod(LinkMovementMethod.getInstance());
mTextView.setText(spannable);
}
and heres the important parts ..declare a selector like this calling it myselector.xml
:
And last in your TextView
in xml do this:
Now you can have a pressed state on your clickableSpan.