我想通过在 MainActivity 中滑动来更改活动。我从 GestureDetectorCompat 声明了一个对象,并在方法 onCreate 中初始化它,如下所示:
gestureObject = new GestureDetectorCompat(MainActivity.this, new GestureListener());
另外,我会覆盖 onTouchEvent :
@Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureObject.onTouchEvent(event);
return super.onTouchEvent(event);
}
我的 MainActivity 从 AppCompatActivity 扩展,并实现 NavigationView.OnNavigationItemSelectedListener,OnMenuItemClickListener 。
GestureListener代码是:
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public void onLongPress(MotionEvent e) {
Log.e(TAG, "long pressed");
super.onLongPress(e);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e(TAG, "on Flig");
if (e2.getX() > e1.getX()) {
Log.e(TAG, "left to right");
}
return true;
}
}
但它不起作用。
是否与 navigationView 相关?
我该怎么办?
答案 0 :(得分:1)
试试这段代码..
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
public class MainActivity extends AppCompatActivity {
private GestureDetectorCompat mDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDetector = new GestureDetectorCompat(MainActivity.this, new SwipeGestureDetector());
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
this.mDetector.onTouchEvent(motionEvent);
return super.onTouchEvent(motionEvent);
}
@Override
public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
super.dispatchTouchEvent(ev);
return mDetector.onTouchEvent(ev);
}
/**
* Swipe Gesture Detector Class for swipe detector.
*/
public class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if(e1 == null || e2 == null)
return false;
if(e1.getPointerCount() > 1 || e2.getPointerCount() > 1)
return false;
else {
try {
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
if(Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > 100 && Math.abs(velocityX) > 1000) {
if ((diffX > 0) || (diffX < 0)) {
// nextActivity();
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
}
}
答案 1 :(得分:0)
试试这个,
@Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureObject.onTouchEvent(event);
return true;
}