是否可以将参数传递给一个片段后,它被添加到一个活动?片段、参数

2023-09-05 05:30:08 作者:乄心中的男神

我知道,当你第一次实例化一个片段,您可以通过使用setArguments(捆绑)参数和检索它们在使用片段getArguments()。

I know that when you're first instantiating a fragment you can pass arguments using setArguments(Bundle) and retrieve them in the fragment using getArguments().

不过,在我的应用程序我有后,他们已经加入到一个活动,将分离并附几次片段。在重新连接,我可能需要通过一个片段的参数,它重新连接之前修改其内容。我可以用setArguments我第一次展示了片段,但在随后的场合,将无法正常工作。该savedInstanceState不会在这种情况下,之前卸下片段工作,我不知道该参数的值。

However, in my app I have fragments that will be detached and attached several times after they've been added to an activity. On re-attach, I may need to pass a fragment an argument to modify its content prior to reattaching it. I can use setArguments the first time I display the fragment, but on subsequent occasions that won't work. The savedInstanceState will not work in this case as I won't know the value of the argument prior to detaching the fragment.

我知道我可以只实现,我会附上这将设置一个参数的片段之前调用一个方法,但它只是好像这是一件可能已经在API中,我只是没有看到它。

I know I could just implement a method that I would call before attaching the fragment that would set an argument, but it just seems like this is something that might already be in the API and I'm just not seeing it.

有什么内置的,让我这样做,否则我将不得不实现这个我自己?为了记录在案,我现在用的是支持包(V4)。

Is there something built-in that will allow me to do this, or will I have to implement this on my own? For the record, I am using the support package (v4).

非常感谢!

推荐答案

您可以直接暴露在你的片段设置任何你想传递给它的方法。要调用它,你可以如按标签检索来自backstack的片段或来自各地保持实例引用无论你是从调用它。

You can just expose a method on your fragment that set whatever you want to pass to it. To call it you can e.g. retrieve the fragment from the backstack by tag or keep an instance reference around from wherever you are calling it from.

这工作得很好,我虽然你需要防守的空支票和等,以及认识到生命周期的条款提出你的片段经历,当你连接,或重新启动它。

This works nicely for me although you need to be defensive in terms of null checks and such as well as aware of the lifecyle your fragment goes through when you attach it or restart it.

从我可以告诉有什么API中...

From what I can tell there is nothing in the API...

更新:这仍然是正确的,工作就好了。我发现,一旦这种更为复杂的是更清洁和更容易使用的东西,如奥托 eventbus。强烈推荐恕我直言。

Update: This is still true and works just fine. I found that once this is more complex it is much cleaner and easier to use something like the Otto eventbus. Highly recommended imho.