How to clear arguments in Fragment?

半城伤御伤魂 提交于 2020-12-02 07:04:58

问题


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

If I have an url key in the getArguments() of my instance of AudioPlayerFragment, I start a service that plays the audio stream. If there was already a stream playing, I stop it and start it again with the new stream.

If there is no arguments, I do nothing.

My problem is that the arguments are kept with the instance, so when I get back to it, getArguments() returns the latest arguments set, if no new have been set.

So after reading them, I try to set the arguments to null with

setArguments(null);

But I get

Java.lang.IllegalStateException: fragment already active

How can I clear the arguments then?


回答1:


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;
}



回答2:


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




回答3:


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.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/17875741/how-to-clear-arguments-in-fragment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!