Onclick on view pager in android does not work in my code

前端 未结 3 1030
谎友^
谎友^ 2021-02-14 06:08

i have implemented view pager in my code and i have put on-click listener on view pager but my on-click listener does not working i\'ll post my code

viewpager.s         


        
3条回答
  •  清酒与你
    2021-02-14 07:11

    I implemented custom ViewPager:

    public class ClickableViewPager extends ViewPager {
    
        private OnClickListener mOnClickListener;
    
        public ClickableViewPager(Context context) {
            super(context);
    
            setup();
        }
    
        public ClickableViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            setup();
        }
    
        private void setup() {
            final GestureDetector tapGestureDetector = new GestureDetector(getContext(), new TapGestureListener());
    
            setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    tapGestureDetector.onTouchEvent(event);
    
                    return false;
                }
            });
        }
    
        public void setOnViewPagerClickListener(OnClickListener onClickListener) {
            mOnClickListener = onClickListener;
        }
    
        public interface OnClickListener {
            void onViewPagerClick(ViewPager viewPager);
        }
    
        private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
    
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if(mOnClickListener != null) {
                   mOnClickListener.onViewPagerClick(ClickableViewPager.this);
                }
    
                return true;
            }
        }
    }
    

    And example how to implement onClickListener:

    ClickableViewPager viewPager = (ClickableViewPager) findViewById(R.id.viewPager);
    mViewPager.setOnViewPagerClickListener(new ClickableViewPager.OnClickListener() {
                @Override
                public void onViewPagerClick(ViewPager viewPager) {
                    //yourCode
                }
            });
    

提交回复
热议问题