Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable tap listener in view pager in Android?

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.

like image 539
Nancy Avatar asked Mar 05 '12 07:03

Nancy


People also ask

How to add ViewPager in android?

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 .

What is onTouch Android?

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.


2 Answers

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;
        }
    });
like image 139
Jorge Aguilar Avatar answered Oct 16 '22 15:10

Jorge Aguilar


We can use Gestures (Link1, Link2):

public boolean onTouchEvent (MotionEvent ev)

Hope this helps!

like image 24
LOG_TAG Avatar answered Oct 16 '22 17:10

LOG_TAG