我正在尝试在我的应用程序中实现滑动手势。我已经编写了几乎所有的代码,但它没有生效。
这是我在Activity中的代码:
// Swipe detector
gestureDetector = new GestureDetector(new SwipeGesture(this));
gestureListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event)
{
Log.e("", "It works");
return gestureDetector.onTouchEvent(event);
}
};
LinearLayout root = (LinearLayout) findViewById(R.id.rules_root);
root.setOnTouchListener(gestureListener);
当我触摸屏幕时,logcat 显示“it works”。
这是类 SwipeGesture 的代码:
public class SwipeGesture extends SimpleOnGestureListener
{
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Activity activity;
public SwipeGesture(Activity activity)
{
super();
this.activity = activity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
Log.e("", "Here I am");
try
{
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false;
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if ( ((TabActivity) activity.getParent()).getTabHost() != null )
{
TabHost th = ((TabActivity) activity.getParent()).getTabHost();
th.setCurrentTab(th.getCurrentTab() - 1);
}
else
{
activity.finish();
}
Log.e("", "Swipe left");
}
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if ( ((TabActivity) activity.getParent()).getTabHost() != null )
{
TabHost th = ((TabActivity) activity.getParent()).getTabHost();
th.setCurrentTab(th.getCurrentTab() + 1);
}
Log.e("", "Swipe right");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
}
这行代码Log.e("", "Here I am");
没有被显示,因此我认为onFling方法没有被调用。
你有什么想法,为什么它不起作用?
谢谢。
祝好。
V.