我想为另一个类的 TextView
设置 ClickableSpan
。在 ClickableSpan
中,我需要重写两个方法:updateDrawState()
和 onClick()
。前一个方法对于所有 TextView
都是相同的,但后者 onClick()
对于任何 TextView
都是不同的。因此,我只想编写一次 updateDrawState()
方法(在 Commons 类 中),而不是为任何 TextView
编写。我怎样才能实现这个目标?
以下代码块清楚地解释了我想要的内容:
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);
}
...
}
和
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();
}
});
...
}
最佳答案
我不确定我是否理解正确,但您可能想创建 updateDrawState
方法和几个 onClick
的通用实现。
您可以通过创建扩展 ClickableSpan
的抽象类并仅实现 updateDrawState
来实现此目的:
public abstract class MyClickableSpan extends ClickableSpan {
@Override
public void updateDrawState(TextPaint ds) {
// Your custom implementation
}
}
然后像这样使用它:
ClickableSpan clickableSpan = new MyClickableSpan() {
@Override
public void onClick(View widget) {
// Your custom implementation
}
};
<小时/>
如果您坚持使用 Commons
类,我可能会将方法设为静态:
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);
}
}
用法:
Commons.makeTextViewSpannable(textView, text, startIndex, endIndex, new MyClickableSpan() {
@Override
public void onClick(View widget) {
// Your custom implementation
}
});
关于java - 从另一个 java 类重写该类中的方法(附加到其他方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197092/