How to save and reuse same instance of fragments?

前端 未结 2 1382
攒了一身酷
攒了一身酷 2021-01-04 02:45

I have recently started using fragments have created a demo app which looks like this:

\"Demo

C

2条回答
  •  无人及你
    2021-01-04 03:32

    The FragmentManager does it's own memory management. It will kill/recreate or keep in memory your instances according to its logic. You can ensure your fragment's state is save using onSaveInstanceState()

    Or you can for force the system to keep your instance alive using setRetainInstance(true) on your Fragment.

    This is how you create a transaction.

        FragmentTransaction fragmentTransaction = context.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.layout, new MyFragment(), f.getClass().getName());
        fragmentTransaction.commit();
    

提交回复
热议问题