Why does rotation cause Android fragment replacement to fail?

后端 未结 2 1639
终归单人心
终归单人心 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:42

    The answer is simple. UI state is retained across screen rotations meaning if you do nothing the screen would still show the second fragment once you rotate. Since you add the first fragment in your Activity onCreate method it will be added to what is already shown hence the two fragments overlap.

    You could do something like this:

    FragmentManager mgr = getFragmentManager();
    if (mgr.findFragmentByTag("start") == null &&
        mgr.findFragmentByTag("replacementTest") == null) {
    
        FragmentTransaction t = mgr.beginTransaction();
        t.add(R.id.fragment_container, startingFragment, "start").commit();             
    
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题