如何清除Fragment中的参数? [英] How to clear arguments in Fragment?

查看:132
本文介绍了如何清除Fragment中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 AudioPlayerFragment ,我使用setArguments()向其传递了一些网址.

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

如果我的 AudioPlayerFragment 实例的 getArguments()中有一个 url 键,则我将启动一个播放音频流的服务.如果已经有流在播放,请停止它,然后使用新的流重新开始.

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.

我的问题是参数与实例保持在一起,所以当我回到实例时,如果未设置新参数,则 getArguments()返回最新的参数集.

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.

因此,在阅读它们之后,我尝试通过以下方式将参数设置为null

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

setArguments(null);

但是我明白了

Java.lang.IllegalStateException: fragment already active

那我怎么清除参数呢?

推荐答案

确保您正在阅读片段的 onCreate()方法中的 getArguments().一旦创建了该片段,回退时就不会通过 onCreate()槽,因此您不应再次读取参数.

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.

类似这样的东西:

if(!argumentsRead){

    // read arguments

    argumentsRead = true;
}

这篇关于如何清除Fragment中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆