我有一个带有滑动侦听器的TextView。我也想添加一个长按一下监听器。它们都可以工作,但是当我滑动时,也会触发长按聆听器,这不是我想要的。我需要他们独立。我发现了一些very old code关于检测长按的问题,但目前还不是很清楚什么是最好的方法。
这是我在MainActivity中的内容
tvIta.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
@Override
public void onSwipeRight() {changeSays(); }
@Override
public void onSwipeLeft() { changeSays(); }
});
tvIta.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String label = "Label_Ita";
String text = tvIta.getText().toString();
ClipboardManager clipboard = (ClipboardManager) getSystemService(MainActivity.this.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(label, text);
clipboard.setPrimaryClip(clip);
Toast.makeText(MainActivity.this, "Copied to clipboard!", Toast.LENGTH_SHORT).show();
return true;
}
});
这是滑动侦听器类
public class OnSwipeTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
// commented out otherwise won't work
// @Override
// public boolean onDown(MotionEvent e) {
// return true;
// }
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}
}
}
谢谢!
答案 0 :(得分:0)
尝试使用布尔值同步两个事件。以下代码是一个示例:
boolean swiped = false;
boolean clicked = false;
tvIta.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
@Override
public void onSwipeRight() {
if(!clicked) {
swiped = true;
changeSays();
}
}
@Override
public void onSwipeLeft() {
if(!clicked) {
swiped = true;
changeSays();
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
swiped = false;
clicked = false;
}
return super(v, event);
}
});
tvIta.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(!swiped) {
clicked = true;
String label = "Label_Ita";
String text = tvIta.getText().toString();
ClipboardManager clipboard = (ClipboardManager) getSystemService(MainActivity.this.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(label, text);
clipboard.setPrimaryClip(clip);
Toast.makeText(MainActivity.this, "Copied to clipboard!", Toast.LENGTH_SHORT).show();
}
return true;
}
});