Handle Fragment duplication on Screen Rotate (with sample code)

后端 未结 4 1997
死守一世寂寞
死守一世寂寞 2021-02-06 11:03

There are some similar answers, but not to this situation.


My situation is simple.

I have an Activity with two different layouts, one in Portrait,

4条回答
  •  难免孤独
    2021-02-06 11:09

    In your onCreate() method you should only create your ListFrag if you are in portrait mode. You can do that by checking if the FrameLayout view that you only have in the portrait layout is not null.

    if (findViewById(R.id.yourFrameLayout) != null) {
        // you are in portrait mode
        ListFrag listFrag = new ListFrag();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.FragmentContainer, listFrag).commit();
    } else {
        // you are in landscape mode
        // get your Fragment from the xml
    }
    

    In the end if you switch from portrait to landscape layout, you don't want to have another ListFrag created, but use the Fragment you have specified in your xml.

提交回复
热议问题