onPageSelected doesn't work for first page

前端 未结 10 2005
[愿得一人]
[愿得一人] 2021-01-30 12:30

My pager adapter ( extends PagerAdepter ) has a textview in it. And I update this textview with MainActivity\'s onPageSelected . Its update textview for position > 0 , but start

10条回答
  •  长情又很酷
    2021-01-30 13:10

    My solution is an extend ViewPager

    class MyViewPager extends ViewPager {
    
        private List _Listeners = new ArrayList<>();
    
        public MyViewPager(Context context) {
            super(context);
        }
    
        public MyViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public void addOnPageChangeListener(OnPageChangeListener listener) {
            super.addOnPageChangeListener(listener);
            _Listeners.add(listener);
        }
    
        @Override
        public void removeOnPageChangeListener(OnPageChangeListener listener) {
            super.removeOnPageChangeListener(listener);
            _Listeners.remove(listener);
        }
    
        @Override
        public void setCurrentItem(final int item) {
            if (item != getCurrentItem()) {
                super.setCurrentItem(item);
            } else {
                post(new Runnable() {
                    @Override
                    public void run() {
                        dispatchOnPageSelected(item);
                    }
                });
            }
        }
    
        private void dispatchOnPageSelected(int position) {
            for (int i = 0, size = _Listeners.size(); i < size; i++) {
                OnPageChangeListener listener = _Listeners.get(i);
                if (listener != null) {
                    listener.onPageSelected(position);
                }
            }
        }
    }
    

提交回复
热议问题