Can't Detect Gesture on a FrameLayout in Android
我想在android中实现一个全局NavigationBar Widget,扩展FrameLayout,这样它就可以在布局xml中声明,而不是包含在每个活动中。
NavigationBar有三个组件:Logo,Title,Button
当触摸或向下按下NavgationBar(不包括按钮)时,我会显示一些内容。但是现在我的onFling手势无法被检测到(SwipeGestureListener中的OnFling已经过测试),任何人都可以帮助我。
类NavigationBar:
1 2 3 4 | public class NavigationBarWidget extends FrameLayout implements View.OnClickListener private SwipeGestureListener mSwipeListener = new SwipeGestureListener(); private GestureDetector mGestureDetector; |
NavigationBarWidget():
1 2 3 4 5 6 7 8 9 10 | mGestureDetector = new GestureDetector(mSwipeListener); this.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.v("Nav","onTouch"); return mGestureDetector.onTouchEvent(event); } }); |
的OnClick():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | @Override public void onClick(View paramView) { if(paramView.getId()== mShareIcon.getId()){ AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext()); builder.setMessage("Are you sure you want to exit?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); }else{ Log.v("Nav","onClick"); } } |
swipeGestureListener中的onFling():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.v("Nav","onFling"); try { if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH) { return false; } else { if ((e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE) && (Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY)) { this.mCallbackListener.onFlingDown(); return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } |
Logcat:当触摸或向下移动导航栏时,已输出"onTouch",但未检测到手势onFling。
我通过阅读Android开发者博客上的帖子解决了这个问题:
理解多点触控。
解决方案是让GestureDetector处理手势,你可以处理触摸事件,然后像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | mGestureDetector = new GestureDetector(mSwipeListener); this.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.v("Nav","onTouch"); mGestureDetector.onTouchEvent(event); final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN:{ Log.v("Nav","onDown"); break; } case MotionEvent.ACTION_UP:{ Log.v("Nav","onUp"); break; } } return true; } }); |
当我向下浏览NavigationBarWidget时,日志将是:
onTouch-> onDown-> onTouch(你可以在屏幕上按多少onTouch) - > onFlingDown-> onUp