onPageSelected doesn't work for first page

前端 未结 10 1994
[愿得一人]
[愿得一人] 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:08

    You can manually call onPageSelected(0) when you create your OnPageChangeListener to set the starting state:

    OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrollStateChanged(int arg0) { }
    
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }
    
        @Override
        public void onPageSelected(int position) {
    
            switch (position) {
            case 0: 
                QuizStart.next.setText(getmycurrentpage()+"");
                break;
    
            default:
    
                QuizStart.next.setText(getmycurrentpage()+"");
                break;
            }
        }
    });
    
       mPager.setOnPageChangeListener(pageChangeListener);
       // do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
       mPager.post(new Runnable()
       {
           @Override
           public void run() 
           {
               pageChangeListener .onPageSelected(viewPager.getCurrentItem());
           }
       });
    

    Edit

    Now it will not get Null Pointer exception as pointed by @metemet06

提交回复
热议问题