When to use FragmentManager::putFragment and getFragment

前端 未结 3 646
醉话见心
醉话见心 2020-12-01 00:15

I\'ve got an application that uses fragments and I was playing around with how to use the same fragment in an Activity with a dual pane and an Activity as a stand alone. Sti

相关标签:
3条回答
  • 2020-12-01 00:35

    You have a nice explanation of what put|getFragment can be used for in this android group thread.

    Although the whole thread is interesting, the real answer to your question was given by Dianne Hackborn"

    You can also take advantage of the FragmentManager APIs to save a fragment "pointer" in a bundle and later retrieve it, to allow you to maintain direct pointers across state save/restore.

    0 讨论(0)
  • 2020-12-01 00:40

    In short, It is just the way that you can retrieve reference of fragment after Activity is restored. For instance, when you create a fragment and use it throughout your activity, so after configuration change, your activity is recreated, you want that reference back. So

    public void onSaveInstanceState(Bundle outState){
       getFragmentManager().putFragment(outState,"myfragment",myfragment);
    }
    public void onRetoreInstanceState(Bundle inState){
       myFragment = getFragmentManager().getFragment(inState,"myfragment");
    }
    
    0 讨论(0)
  • 2020-12-01 00:43

    The basic answer:

    These are only useful when implementing onSaveInstanceState() and restoring that state in onCreate(). If you are not implementing onSaveInstanceState(), you can forget about these methods and pretend like they don't exist.

    The problem they are solving: if you want to save a reference to a fragment in your "saved instance state," you can't just put an object reference in there. First because well you can't put plain object in a Bundle. :) And the reason for this is that the point of that saved state is for it to be copied out of your process, so if your process needs to be killed, it can later be copied back in to a new process for you to re-initialize your activity/fragment from. A raw object is only meaningful in the context of the process it is running in, so it isn't possible to correctly copy the reference to such an object out of your current process and in to another.

    So what putFragment()/getFragment() do is place a piece of data in the given Bundle that can identify that fragment across to a new instance of your activity/fragment in another process. Exactly what this representation is, is not defined, but in the current implementation it is the internal integer identifier for that fragment, which will be used later when the FragmentManager needs to re-create that fragment from a previously saved state... it is re-created with that same identifier, so when you then call getFragment() it can retrieve the integer, and use that to determine the correct Fragment object to return to the caller that corresponds to the one that was previously saved.

    0 讨论(0)
提交回复
热议问题