Why does rotation cause Android fragment replacement to fail?

后端 未结 2 1650
终归单人心
终归单人心 2020-12-21 16:07

I have put together a simple program that uses fragment replacement with a single activity and two fragments. One fragment has a button, that when pressed, replaces the frag

2条回答
  •  执念已碎
    2020-12-21 16:44

    @Emanuel is correct that the UI state is retained across screen rotations. However what's happening is simply that your Activity's onCreate is always called on rotation, which always adds your startingFragment

    The solution is simple. Just add a condition in your onCreate as so to handle the case when it's called as part of the activity lifecycle:

    if (savedInstanceState == null)
            {
                FragmentTransaction t = getFragmentManager().beginTransaction();
                t.add(R.id.fragment_container, startingFragment, "start").commit();
            }
    

    You might want to consider doing

    t.replace(R.id.fragment_container, startingFragment, "start").commit();
    

    though instead of

    t.add(R.id.fragment_container, startingFragment, "start").commit();
    

提交回复
热议问题