Why does rotation cause Android fragment replacement to fail?

后端 未结 2 1651
终归单人心
终归单人心 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();             
    
    }
    

提交回复
热议问题