我使用我自己的GestureDetector類來檢測左側|右側onFling事件。我看到的所有內容在我的代碼中看起來不錯,但沒有任何反應......爲什麼我的SimpleOnGestureListener無法正常工作?
我需要添加的功能超出了我的切換按鈕,該按鈕可打開我的片段中的導航視圖。撥動調用的方法在我AnimationLayout類,如下所示:
public void toggleSidebar()
{
if (mContent.getAnimation() != null)
{
return;
}
if (mOpened)
{
/* opened, make close animation */
mAnimation = new TranslateAnimation(0, -mSidebarWidth, 0, 0);
mAnimation.setAnimationListener(mCloseListener);
} else
{
/* not opened, make open animation */
mAnimation = new TranslateAnimation(0, mSidebarWidth, 0, 0);
mAnimation.setAnimationListener(mOpenListener);
}
mAnimation.setDuration(DURATION);
mAnimation.setFillAfter(true);
mAnimation.setFillEnabled(true);
mContent.startAnimation(mAnimation);
}
和...
public void openSidebar()
{
if (!mOpened)
{
toggleSidebar();
}
}
public void closeSidebar()
{
if (mOpened)
{
toggleSidebar();
}
}
在我的主要活動的onFling()調用上的切換子:
public static AnimationLayout mLayout;
// these constants are used for onFling
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 GestureDetector gestureDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (AnimationLayout) findViewById(R.id.animation_layout);
gestureDetector = new GestureDetector(this.getApplicationContext(), new MyGestureDetector());
// Set the touch listener for the main view to be our custom gesture
// listener
mLayout.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
});
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
return false;
}
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(getApplicationContext(), "right_left", Toast.LENGTH_LONG).show();
Log.i("MyGestureDetector", "R2L!");
mLayout.closeSidebar();
// left to right swipe
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(getApplicationContext(), "left_right", Toast.LENGTH_LONG).show();
Log.i("MyGestureDetector", "L2R!");
mLayout.openSidebar();
}
return false;
}
// Return true from onDown for the onFling event to register
@Override
public boolean onDown(MotionEvent e) {
return true;
}
}
此按鈕正常工作:
...
case R.id.navToggleBtn : {
mLayout.toggleSidebar();
}
...
你可以驗證你的'TouchListener'是否接收所有事件讓它們轉發?如果您的佈局包含可觸摸的子項,則他們可能會從其父項(您的佈局)中竊取事件。 – Devunwired
我想你可能是對的。我將把這個函數放在一個子佈局上,然後看看。 – CelticParser