How to clear arguments in Fragment?

后端 未结 5 1420
Happy的楠姐
Happy的楠姐 2021-02-20 01:58

I have an AudioPlayerFragment to which I pass some url with setArguments().

If I have an url key in the getArguments() of my insta

相关标签:
5条回答
  • 2021-02-20 02:09

    Make sure you are reading getArguments() in onCreate() method of the fragment. Once the fragment was created, when going back you souldn't pass trough onCreate(), so you shouldn't be able to read again the arguments.

    If this still does not work, you could make use of a boolean flag and read the arguments only once.

    Something like this:

    if(!argumentsRead){
    
        // read arguments
    
        argumentsRead = true;
    }
    
    0 讨论(0)
  • 2021-02-20 02:11

    I have come across situations where you want to remove the arguments in a fragment. for example, entering a fragment for the first time maybe you have up to date data, but afterwards on a fragment re-creation you do not want that data, you want to refresh. you could clear a element in the bundle like this:

    getArguments().remove("cartDetails");
    

    for my case i wrote about, i put that in onCreate of the fragment after getting the initial data.

    0 讨论(0)
  • 2021-02-20 02:14

    Do not try to change the argument. Instantiate the Fragment again with no argument and replace it with the old one.

    If you do not want to recreate the UI and only try to change the music or audio, you can decouple the audio functions from your fragment and put them in a Headless Retained Fragment and you are good to go.

    0 讨论(0)
  • 2021-02-20 02:23

    Call this.getArguments().clear(); in onDestroyView() method in your fragment.

    0 讨论(0)
  • 2021-02-20 02:29

    Mutating Bundle returned by getArguments() lies in gray area. You don't know and shouldn't presume how Fragment uses that Bundle instance.

    Ask yourself what happens:

    • if they decide to change getArguments() to always return different bundle instance (defensive copy)

    • or if you change arguments at wrong time

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