1
我試圖讓一個滑動手勢在EditText上工作。 但是,我嘗試的所有東西往往是越野車。Android handeling在編輯文本上滑動手勢
當我返回false時,手勢起作用,但光標在進行滑動手勢時移動。 但是,當我從GestureListener(onFling)返回結果時,光標停留在原位,但在手勢完成後,在Android 2.3.3上彈出文本編輯的上下文菜單,在4.1.2上沒有上下文菜單,但是使手勢選擇一個單詞。
這裏是我當前的代碼:
package com.example.testmarkup;
import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class OnSwipeTouchListener implements OnTouchListener {
public interface OnSwipeListener {
public void OnSwipe();
}
private GestureDetector mGestureDetector = null;
private OnSwipeListener mOnSwipeLeftListener;
private OnSwipeListener mOnSwipeRightListener;
private GestureListener mGestureListener = null;
public OnSwipeTouchListener(final Context context) {
mGestureListener = new GestureListener();
mGestureDetector = new GestureDetector(context, mGestureListener);
}
public boolean onTouch(final View view, final MotionEvent motionEvent) {
final boolean result = mGestureDetector.onTouchEvent(motionEvent);
//When I return false here the gesture works but the cursor moves when making a swipe gesture.
//However when I return the result from the GestureListener (onFling) the cursor stay's in place,
//but on Android 2.3.3 after the gesture is finished the context menu from the text edit pops up,
//on 4.1.2 there is no context menu, but making the gesture will select a whole word.
// return false;
return result;
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) {
boolean result = false;
try {
final float diffY = e2.getY() - e1.getY();
final float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
result = true;
} else {
onSwipeLeft();
result = true;
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
result = true;
} else {
onSwipeTop();
result = true;
}
}
}
} catch (final Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
if (mOnSwipeRightListener != null)
mOnSwipeRightListener.OnSwipe();
}
public void onSwipeLeft() {
if (mOnSwipeLeftListener != null)
mOnSwipeLeftListener.OnSwipe();
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
public OnSwipeTouchListener setOnSwipeLeft(final OnSwipeListener aListener) {
mOnSwipeLeftListener = aListener;
return this;
}
public OnSwipeTouchListener setOnSwipeRight(final OnSwipeListener aListener) {
mOnSwipeRightListener = aListener;
return this;
}
}