我有一个文本视图和其中的链接。我希望在触摸它们时突出显示链接,并且我希望在长按它们时打开一个警报对话框。我试图通过自定义 URLSpan 来获得解决方案,但是,由于在调用 OnClick 之前我无法访问 mView,因此我无法设置侦听器:
class ConfirmSpan extends URLSpan{
View mView;
URLSpan span;
public ConfirmSpan(URLSpan span) {
super(span.getURL());
this.span = span;
//there is a nullpointerexception here since mView is null now.
mView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
((TextView)v).setBackgroundColor(0xcccccccc);
return false;
}
});
//this is also an exception
mView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.d("INFO","long click yay!");
return false;
}
});
}
//this should be called to reach the view. But then I can't handle touch state.
@Override
public void onClick(View widget) {
mView = widget;
//bla bla..
}
public void openURL() {
super.onClick(mView);
}
}
我想我必须自定义 LinkMovementMethod 类但如何?任何评论将不胜感激。更新:我现在可以使用以下代码处理触摸事件:
public class CustomLinkMovementMethod extends LinkMovementMethod {
private static CustomLinkMovementMethod sInstance;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
// Here I am changing backgorund color
if(event.getAction() == MotionEvent.ACTION_DOWN)
widget.setBackgroundColor(0xcccccccc);
if(event.getAction() == MotionEvent.ACTION_UP)
widget.setBackgroundColor(0xffffffff);
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new CustomLinkMovementMethod();
return sInstance;
}
}
但是TextView命名的小部件,一个参数OnTouchEvent(),不是我想要的。这是所有的文本。因此,当我触摸链接时,文本完全变为灰色。我认为我需要一些其他方法,例如通过查找链接的起点和终点线的坐标来为链接的背景着色。