How do I implement Fragment data in Android ViewPager?

Asked 2 years ago, Updated 2 years ago, 167 views

Due to the nature of the view phaser in the Android view phaser, the current view and the view before the next view are called together. Assuming that there are about five fragments in the viewfager, When the current fragment was 2, I was calling up fragments 1 and 3. However, if I go to fragment 5 and come back to fragment 2, I will load the data again, but I want to know how to use the original fragment data again.

In conclusion, I don't want to erase the data in the fragment, but I want to save it somewhere and reload it What should I do?

android android-viewpager

2022-09-22 21:37

1 Answers

If you want to save the state value when the fragment is terminated, inherit the FragmentStatePagerAdapter and create an adapter. You can then override the fragment's onSaveInstanceState. The onSaveInstanceState function can store data in the Bundle that is called before the fragment is terminated and passed to the parameter, and eject the data stored in the Bundle in the onCreate/onCreateView when the fragment is generated again.

Fragment (Pseudo-code)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (savedInstanceState != null && savedInstanceState.get("data") != null) {
       // Use previously stored data
       ...

    }
    return view;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // Save Data
    outState.putInt("data", "XXX");
}

In addition, if you have a fixed number of pages in ViewPager and want to keep the fragments in memory when swiping, use the setOffscreenPageLimit(intlimit) function in ViewPager. This is the easiest way to maintain the state of the fragment.


2022-09-22 21:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.