I want to set ClickableSpan
for a TextView
from another class. In ClickableSpan
I need to override two methods, updateDrawState()
and onClick()
. The former method is the same for all TextViews
, but the latter, onClick()
, is different for any TextView
. So I want write updateDrawState()
method only once (in the Commons class), not for any TextView
. How can I achieve this?
The following code blocks clearly explain what I want:
public class Commons {
...
public void makeSpannable(TextView tv, String text, int startIndex, int endIndex, ClickableSpan appendClickableSpan) {
SpannableString span = new SpannableString(text);
span.setSpan({
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ContextCompat.getColor(Activation.this, R.color.textViewClickable));
ds.setUnderlineText(false);
appendClickableSpan;
}}, startIndex, endIndex, 0);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(span, TextView.BufferType.SPANNABLE);
}
...
}
and
public class Main {
...
TextView textView = findViewById(R.id.textView1);
String text = "some sample text";
new Commons().makeSpannable(textView, text, 2, 6, new ClickableSpan() {
@Override
public void onClick(View widget) {
if (validator.checkValidation(tilCode)) ResendActivationEmail();
}
});
...
}
I am not sure, if I understand you correctly, but you probably want to create common implementation of updateDrawState
method and several of onClick
.
You could achive this by making abstract class where you extends ClickableSpan
and only implement updateDrawState
like this:
public abstract class MyClickableSpan extends ClickableSpan {
@Override
public void updateDrawState(TextPaint ds) {
// Your custom implementation
}
}
And then use it like this:
ClickableSpan clickableSpan = new MyClickableSpan() {
@Override
public void onClick(View widget) {
// Your custom implementation
}
};
If you insist on Commons
class, I probably make the method static:
public class Commons {
public static void makeTextViewSpannable(TextView tv, String text, int startIndex, int endIndex, MyClickableSpan span) {
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(span, startIndex, endIndex, 0);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(spannableString, TextView.BufferType.SPANNABLE);
}
}
Usage:
Commons.makeTextViewSpannable(textView, text, startIndex, endIndex, new MyClickableSpan() {
@Override
public void onClick(View widget) {
// Your custom implementation
}
});