When multiple fragments are switched, switch to the background and then come in, causing fragments to overlap

1. Questions:

        When the mobile phone setting is turned on to not keep the activity, when multiple fragments are switched, they will cut into the background and come in again, causing the fragments to overlap

2. Analysis:

        This is because when switching to the background, the activity will be recycled and rebuilt, causing all life cycles to be re-executed, but the fragment in the activity will not be recycled, causing the fragment to be created multiple times, causing various problems

Three, to solve:        

        onSaveInstanceState is called before the Activity is destroyed to save the state of each instance, so that the state can be restored from onCreate(Bundle) or onRestoreInstanceState(Bundle).

        Taking advantage of this, the data can be saved first, and when the interface is restored, the saved data can be obtained for processing

4. Case:

1. Call onSaveInstanceState() to save the data you want to save

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        //保存fragment的索引
         outState.putInt(SAVED_CURRENT_ID, currentItemIndex);
    }

 2. Get the saved data in onCreate or onRestoreInstanceState

        //获取fragment索引
        if (savedInstanceState != null) {
            currentItemIndex = savedInstanceState.getInt(SAVED_CURRENT_ID);
        }

3. Set the index currentItemIndex = index when the tab switches fragments

4. When setting the default data, set the index

V. Summary:

        To solve the problem caused by pressing the background, the solution idea is the same, save the state in onSaveInstanceState, and restore the state in onCreate or onRestoreInstanceState

        

Guess you like

Origin blog.csdn.net/weixin_42277946/article/details/130235447