Overlapping hidden fragments after application get

2019-01-21 06:45发布

I'm switching between fragments by hiding the last fragment and adding a new one (See code below) - adding it to the back-stack as well. This way, users can quickly switch between the fragments without reloading the fragment data.

This works well until the app is killed (Scenario: users uses several other apps and my app is getting persisted and killed).

When a user opens the app, it is being restored and all the fragments are shown - overlapping one another.

Question: How can the restored fragments be restored with their hidden state? Perhaps I'm missing some flag? somewhere? Perhaps there is a better solution for fast switching between fragments (without reloading the data)?

Sample code of adding fragments - invoked several times with different fragments upon clicking somewhere:

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(lastFragment);
fragmentTransaction.add(newFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
lastFragment = newFragment;

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-21 07:36

I met the same problem,I think this is Android framework bug.Here is the issue.

However my way will work for you, we should override the onSaveInstanceState(Bundle outState) method, save our custom data to outState, but never to call super.onSaveInstanceState(outState);.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ......

    if (savedInstanceState != null) {
        mCustomVariable = savedInstanceState.getInt("variable", 0);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    //super.onSaveInstanceState(outState);
    outState.putInt("variable", mCustomVariable);
}
查看更多
登录 后发表回答