Stop fragment from being recreated after resume?

家住魔仙堡 提交于 2020-01-11 00:44:09

问题


I am using several fragments to be dynamically added into activity. Everything works fine, when I press back-button, the fragments 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 fragments from recreating. I tried with onSavedInstanstate but nothing is working. How can I accomplish that?


回答1:


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().




回答2:


In the Activity's onCreateView set the savedInstanceState to null before calling the super method. You could also remove only the keys "android:viewHierarchyState" and "android:fragments" from the savedInstanceState bundle. Here is code for the simple solution, nulling the state:

@Override
public void onCreate(Bundle savedInstanceState)
{
    savedInstanceState = null;
    super.onCreate(savedInstanceState);

    ...
}



回答3:


Iam using 5 fragments and working for me good as I was facing the same issue before..

public class MyFragmentView1 extends Fragment {

    View v;
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, 
                @Nullable Bundle savedInstanceState) {
        if (v == null) 
            v = inflater.inflate(R.layout.my_fragment_view_layout, 
                container, false
            );
        return v;
    }
}

I put the view variable inside class and inflating it as new only if the view instance is null or otherwise use the one created before



来源:https://stackoverflow.com/questions/18428152/stop-fragment-from-being-recreated-after-resume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!