Kaidul Islam Kaidul Islam - 5 months ago 40
Android Question

Stop fragment from being recreated after resume?

I am using several

fragment
s to be dynamically added into
activity
. Everything works fine, when I press back-button, the
fragment
s go to
backstack
. And when I
resume
it, it appears. But everytime on
Resume
, it is recreating the
fragment
and call
onCreateView
. I know it is a normal behavior of the
fragment
lifecycle.

This is my
onCreateView
:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.competitive_programming_exercise, container, false);
return rootView;
}


I want to stop those
fragment
s from recreating. I tried with
onSavedInstanstate
but nothing is working. How can I accomplish that?

Answer

You can't stop the fragment from being recreated, unfortunately. The best you can do is to remove the fragment in a transaction, after it has been restored but before it gets displayed.

If you know you are going to remove the fragment immediately you can reduce the performance hit of restoring the fragment by simplifying methods such as onCreateView() to return a dummy view, rather than inflating the whole view hierarchy again.

Unfortunately the tricky part is finding the best place to commit this transaction. According to this article there are not many safe places. Perhaps you can try inside FragmentActivity.onResumeFragments() or possibly Fragment.onResume().