Answer the question
In order to leave comments, you need to log in
Is my option of saving fragment state in android good?
Good afternoon, I am writing a project for android and have been suffering with one problem for a very long time, after a while I found a more or less normal solution, but I'm not sure if it's good.
What is the actual question, every time we create a fragment and initialize it via
onCreateView , we always call inflater.inflate(R.layout.fragment_controller, container, false); , and this operation is quite expensive both in terms of resources and time, some buttons or other visual objects can be generated via asynctask , but in the case when we cannot programmatically create objects, we have to use inflate . I found out that you can add fragments to fragmentMangerin this way and then just hide them and show them.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (!fragmentsAdd[FRAGMENT_CURRENT]) {
fragmentTransaction.add(R.id.container, fragments[FRAGMENT_CURRENT], fragmentsTag[FRAGMENT_CURRENT]);
fragmentsAdd[FRAGMENT_CURRENT] = true;
}
for (int i = 0; i < fragments.length; i++) {
if (i == FRAGMENT_CURRENT)
fragmentTransaction.show(fragments[i]);
else if (fragmentsAdd[i])
fragmentTransaction.hide(fragments[i]);
}
fragmentTransaction.commit();
Answer the question
In order to leave comments, you need to log in
There is an API, so you can do it. But in general, this is not a very good practice, since memory consumption is growing. And if links to some large images remain in the views, then OOM can happen
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question