Touch or Click event ViewPagerIndicator in Android

為{幸葍}努か 提交于 2019-11-29 08:38:33

I also had a same issue. First I created a CustomViewPager, which extends ViewPager:

and override onTouch and onInterceptTouch events:

    public class CustomViewPager extends ViewPager {


        public CustomViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
        }   

        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {

            return super.onInterceptTouchEvent(event);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event){
            return super.onTountEvent(event);
        }

    }

Your xml should be:

    <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="7" />

Change it to

    <com.yourpackage.CustomViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="7" />

For click event use GestureDetector. Sending MotionEvent to the tapGestureDetector.

tapGestureDetector = new GestureDetector(this, new TapGestureListener());

    viewPager.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                tapGestureDetector.onTouchEvent(event);
                return false;
            }
    });

If you are using the compatibility library, you can change the first line to:

tapGestureDetector = new GestureDetectorCompat(this, new TapGestureListener());

You can handle your Event in the GestureListener:

class TapGestureListener extends GestureDetector.SimpleOnGestureListener{

     @Override
     public boolean onSingleTapConfirmed(MotionEvent e) {
       // Your Code here
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!