SetCurrentItem ViewPager2 after notifying changes in adapter not animating

Viewed 739

I am using the ViewPager2 class and i am working with a mutable collection of Fragments. I have a dynamic ViewPager2 which contains initially a unique fragment at rank 0. I also have 2 buttons in this fragment.

According to which button is being clicked, a new fragment is added inside the Adapter's fragment list and i am calling this method :

myAdapter.notifyItemRangeChanged(viewPager.getCurrentItem() + 1, myAdapter.getItemCount())

I can also use notifyItemChanged(viewPager.getCurrentItem() + 1) it's working.

The problem is that i call setCurrentItem(viewPager.getCurrentItem() + 1, true) right after the notify call and it's like if the PageTransformer was not called <=> the smoothscroll is not working.

I thought it was because of some delay between the notify-action and the call of setCurrentItem() but it appears it is not. What i did is :

new Handler().postDelayed(() -> { viewPager.setCurrentItem(...) }, 200)

I have also tried to do : viewPager.post(() -> viewPager.setCurrentItem(...)) but it doesn't help either.

Here is my adapter class :

 private class ViewPagerAdapter extends FragmentStateAdapter {

        ArrayList<Fragment> fragmentArrayList;

        public ProfileViewPagerAdapter(@NonNull FragmentActivity fragmentActivity, ArrayList<Fragment> fragments) {
            super(fragmentActivity);
            this.fragmentArrayList = fragments;
        }
        
        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentArrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean containsItem(long itemId) {
            return super.containsItem(itemId);
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return fragmentArrayList.size();
        }
    }

In the adapter class, I have also tried without overriding getItemViewType(int position), then with the super call in getItemId(int position) and finally without all above methods except getItemCount() and createFragments(int position).

All resultats are the same.

What else can i try ? Thanks

0 Answers
Related