Handle Fragment duplication on Screen Rotate (with sample code)

后端 未结 4 1926
死守一世寂寞
死守一世寂寞 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:13

    I finally come up with a solution to prevent unwanted Fragment re-creating upon the Activity re-creates. It is like what i mentioned in the question:

    The only neat way i found is doing getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.FragmentContainer)).commit(); in onSaveInstanceState(). But it will raise another problems...

    ... with some improvements.

    In onSaveInstanceState():

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (isPortrait2Landscape()) {
            remove_fragments();
        }
        super.onSaveInstanceState(outState);
    }
    
    private boolean isPortrait2Landscape() {
        return isDevicePortrait() && (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
    }
    

    and the isDevicePortrait() would be like:

    private boolean isDevicePortrait() {
        return (findViewById(R.id.A_View_Only_In_Portrait) != null);
    }
    

    *Notice that we cannot use getResources().getConfiguration().orientation to determine if the device is currently literally Portrait. It is because the Resources object is changed RIGHT AFTER the screen rotates - EVEN BEFORE onSaveInstanceState() is called!!

    If we do not want to use findViewById() to test orientation (for any reasons, and it's not so neat afterall), keep a global variable private int current_orientation; and initialise it by current_orientation = getResources().getConfiguration().orientation; in onCreate(). This seems neater. But we should be aware not to change it anywhere during the Activity lifecycle.

    *Be sure we remove_fragments() before super.onSaveInstanceState().

    (Because in my case, i remove the Fragments from the Layout, and from the Activity. If it is after super.onSaveInstanceState(), the Layout will already be saved into the Bundle. Then the Fragments will also be re-created after the Activity re-creates. ###)

    ### I have proved this phenomenon. But the reason of What to determine a Fragment restore upon Activity re-create? is just by my guess. If you have any ideas about it, please answer my another question.

提交回复
热议问题