Home > Blockchain >  Losing fragment in viewpager2
Losing fragment in viewpager2

Time:08-04

when i'm selecting a month on a calendarview in a different fragment or when i rotate the screen, i'm losing the "on hold" fragments. but when i start to swipe all the fragment are acting normally again. I suppose it's related to the life cycle of my application but i'm having trouble to find how to solve this.

i'm using also

            android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"

in my manyfest to keep the state of my buttons on one of my fragment.

what did i miss ?

CodePudding user response:

you can use savedInstanceState or viewModel (I would suggest for first one) in android. So, viewPager has ViewPager.onPageChangeListener(refer to this SO answer https://stackoverflow.com/a/11294494/12649627). So, essentially you activity or fragment should look like this

Java soln:

public class MyFragment extends Fragment {
    private int pagerPosition = 0;
    private final static String PAGER_POSITION_TAG = "PAGER_POSITION_TAG";
    private ViewPager2 myViewPager;
    private ViewPager2.OnPageChangeCallback callback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            pagerPosition = position;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            pagerPosition = savedInstanceState.getInt(PAGER_POSITION_TAG, 0);
        }
        return inflater.inflate(R.layout.my_fragment, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        myViewPager = view.findViewById(R.id.my_view_pager);
        myViewPager.setCurrentItem(pagerPosition);
        myViewPager.registerOnPageChangeCallback(callback);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(PAGER_POSITION_TAG, pagerPosition);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        myViewPager.unregisterOnPageChangeCallback(callback);
    }
}

P.s.: I found out that there is something known as registerOnPageChangeCallback and unregisterOnPageChangeCallback. So I used those. Ignore above code.

  • Related