Home » Android » android – viewpager setonpagechangelistener deprecated

android – viewpager setonpagechangelistener deprecated

Posted by: admin March 10, 2020 Leave a comment

Questions:

Today I’m trying to set ViewPager.setOnPageChangeListener and I’ve found out that it’s deprecated.

How to&Answers:

ViewPager.setOnPageChangeListener is deprecated now. Need to use ViewPager.addOnPageChangeListener instead.

for example,

ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

You can find this Here.

Answer:

this worked for me:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {       
        conterchange.setText(""+(1+position));
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
});

Answer:

Use ViewPager.addOnPageChangeListener instead of ViewPager.setOnPageChangeListener.

Answer:

Just in case someone needs the solution in kotlin:

viewPager.addOnPageChangeListener (object: ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(state: Int) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun onPageSelected(position: Int) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

    })

Answer:

You can achieve via SimpleOnPageChangeListener
Below is the Code:

private Fragment page = null;
/** Defining a listener for pageChange */
        ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);

                page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager_selectPhotos + ":" + position);

                System.out.println(page);
                switch (position) {
                case 0:

                    break;
                case 1:

                    break;

                default:
                    break;
                }
            }
        };
        /** Setting the pageChange listener to the viewPager */
        _pager.setOnPageChangeListener(pageChangeListener);