接受的答案很好。但是我还有一个额外的问题:当我在 textview 中有一些选择文本时,我想点击 textview 以仅取消选择文本 - 而不执行点击侦听器。并且仅在没有文本选择的情况下单击执行。所以下面是我的解决方案:
@SuppressLint("ClickableViewAccessibility")
public static void setOnClickGestureDetectorListener(TextView textView, Context context, View.OnClickListener onClickListener){
if (textView == null || context == null || onClickListener == null)){
return;
}
final GestureDetectorCompat detector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener());
detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
onClickListener.onClick(textView);
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return false;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
});
textView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if ( v instanceof TextView ) {
TextView textView = (TextView)v;
if (textView.getSelectionStart() >= 0 && textView.getSelectionEnd() > textView.getSelectionStart()){
return false;
}
detector.onTouchEvent(event);
}
return false;
}
});
}
调用示例如下:
setOnClickGestureDetectorListener(textView, getContext(), new View.OnClickListener() {
@Override
public void onClick(View v) {
// This is where u add your OnClick event
}
});