How to keep fragment view state?

2020-05-06 16:58发布

问题:

I have doubt in fragment system.

I have two fragments like A and B

If i move A to B,

Navigation.findNavController(v).navigate(R.id.B)

Now A fragment onDestroyView is called i know it's normal. After in B Fragment i called PopBackStack

Navigation.findNavController(v).popBackStack()

now A fragment onViewCreated is called i also know it's normal. Now A fragment all ui is initial state.

My question is how to keep A fragment UI State like recyclerview scroll position, FAB button visibility, etc

回答1:

You have to store recyclerview scroll position, FAB button visibility in a variable and set those values after onViewCreated is called.

OR

You can store it in Bundle of onSaveInstanceState and retain its state

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}