I am using view pager to swipe between the views in Android. Now I need to capture tap event for each of the views. when I override the touch listener to capture the tap event, the swipe action doesn't happen and the screen remains in the first page itself. How do I add touch listener to view pager?
Code:
viewPager.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event)
{
mDetector.onTouchEvent(event);
return true;
}});
For the above code I am able to capture tap event, but the swipe action becomes Impossible.
You can create swipe views using AndroidX's ViewPager widget. To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .
onTouch. Added in API level 1. public abstract boolean onTouch (View v, MotionEvent event) Called when a touch event is dispatched to a view. This allows listeners to get a chance to respond before the target view.
Here i leave you a snippet from my code to detect a "click" on the OnTouchListener, i hope it helps
mImagePager.setOnTouchListener(new OnTouchListener() {
private float pointX;
private float pointY;
private int tolerance = 50;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_MOVE:
return false; //This is important, if you return TRUE the action of swipe will not take place.
case MotionEvent.ACTION_DOWN:
pointX = event.getX();
pointY = event.getY();
break;
case MotionEvent.ACTION_UP:
boolean sameX = pointX + tolerance > event.getX() && pointX - tolerance < event.getX();
boolean sameY = pointY + tolerance > event.getY() && pointY - tolerance < event.getY();
if(sameX && sameY){
//The user "clicked" certain point in the screen or just returned to the same position an raised the finger
}
}
return false;
}
});
We can use Gestures (Link1, Link2):
public boolean onTouchEvent (MotionEvent ev)
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With