简体   繁体   中英

Losing fragment in viewpager2

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?

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);
    }
}

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

in the end this:

binding.activityMainViewpager.setOffscreenPageLimit(2);

have solved the rest of my issue ^^'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM