Home » Android » android – ViewPager's onPageSelected never called

android – ViewPager's onPageSelected never called

Posted by: admin June 15, 2020 Leave a comment

Questions:

I need to implement setOnPageChangeListener because i need to hide certain item from ActionBar if the first fragment is showed to the user.

My simple code :

    viewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int page) { //never called
            // TODO Auto-generated method stub
            if(page == 0)
            {
                isSearch = false;
            }
            else
            {
                isSearch = true;
            }
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });
viewPager.setCurrentItem(0); //not working

If the first fragment is shown (page == 0), isSearch should be false but the onPageSelected never getting called when i debug it.

Please kindly help me, Thanks for your help.

Note : My adapter does not implements OnPageChangeListener. Or should i implement it? Is it a must?

How to&Answers:

If you are using PageIndicator in conjunction with the Viewpager then the onPageChangeListener of the ViewPager is not called. You should set a page change listener to the PageIndicator and it will be called when the page changes.

indicator.setOnPageChangeListener(new OnPageChangeListener() {

    @Override
    public void onPageSelected(int page) {
        if(page == 0)
        {
            isSearch = false;
        }
        else
        {
            isSearch = true;
        }
        supportInvalidateOptionsMenu();
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }
});

Hope this will help you ツ