正确检测在Android中放置在ViewPager内的GridView上的滑动 [英] Correctly detecting a swipe on a GridView placed inside a ViewPager in Android
问题描述
我有一个ViewPager,它使用GridViews作为页面.我希望ViewPager在屏幕上滑动时可以切换页面.
I have a ViewPager which uses GridViews for pages. I would like the ViewPager to switch pages when I swipe across the screen.
问题是在GridView上进行滑动时未检测到滑动.在GridView外部,滑动可以正常工作.似乎GridView捕获了所有触摸事件,而没有先将其传递给ViewPager.
The problem is that swipes are not detected when they are made across the GridView. Outside of the GridView, the swipes work correctly; it seems that the GridView is trapping all touch events without passing it to ViewPager first.
在摆弄源代码的同时,我对从GridView扩展的自定义类进行了此操作:
While fiddling with the source code, I did this to a custom class extended from GridView:
@Override
public boolean onTouchEvent(MotionEvent event) {
return pager.onInterceptTouchEvent(event);
}
-其中 pager
指的是ViewPager类.这样,ViewPager可以正确检测滑动并相应地移动页面,但是它不允许GridView接受任何事件,因此我无法单击这些项目.
-- where pager
refers to the ViewPager class. With this, ViewPager will correctly detect swipes and move pages accordingly, but it doesn't allow GridView to accept any events, so I can't click on the items.
我想做的是正确检测ViewPager中的滑动和GridView上的项目单击.
What I would like to be able to do is correctly detect swipes in ViewPager and item clicks on GridView.
推荐答案
我对colig的实现有麻烦,但是我可以通过继承ViewPager并重写onInterceptTouchEvent()方法来使其工作.我只检查了X方向上的滑动,以便在必要时进行垂直滚动.
I had trouble with colig's implementation, but I was able to get it to work by subclassing ViewPager and overriding the onInterceptTouchEvent() method. I only checked for swipes in the X direction to allow for vertical scrolling if necessary.
private static final int minSwipeDistance = 30;
private float mTouchX;
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean response = super.onInterceptTouchEvent(event);
float x = event.getX();
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTouchX = x;
break;
case MotionEvent.ACTION_MOVE:
float dX = Math.abs(x - mTouchX);
if (dX > minSwipeDistance)
return true;
break;
}
return response;
}
这篇关于正确检测在Android中放置在ViewPager内的GridView上的滑动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!