我不知道是否调用 setArguments
后立即它的实例创建的任何问题的片段。
I'm wondering if calling setArguments
on a Fragment immediately after its instantiation creates any problems.
举例来说,假设我们有下面的代码片段:
For example, say we have the following snippet:
Fragment myFragment = new CustomFragment();
Bundle args = new Bundle();
args.putBoolean("amIAnArg", true);
myFragment.setArguments(args);
这code似乎做工精细,虽然它看起来像code的应的创造竞争条件,因为一个片段的参数只能之前可以设置的 onAttach
方法被调用。
This code seems to work fine, although it looks like the code should create a race condition since a Fragment's arguments can only be set before the onAttach
method is called.
有没有以这种方式设置一个片段的参数中的任何问题?
Are there any issues with setting a Fragment's arguments in this way?
推荐答案
就像一个活动
,片段
有一个特定的生命周期,而不是创造喜欢简单Java对象。当你提交 FragmentTransaction
,它是异步的,并不会立即连接或创建的。它排队的主线程在稍后的时间发生。只有这样,它通过它的生命周期方法(如的onCreate()
, onAttach()
)。
Just like an Activity
, Fragments
have a specific lifecycle, and are not "created" like simple Java objects. When you commit a FragmentTransaction
, it's asynchronous and isn't immediately attached or created. It's queued on the main thread to occur at a later time. Only then will it go through its lifecycle methods (e.g. onCreate()
, onAttach()
).
您应的设置参数这种方式,在提交之前应该这样做的 FragmentTransaction
- 然而,你可以在技术上做是正确的后犯有没有不良影响的交易。正如其他人所指出的,你在做什么是碎片建议的newInstance()
工厂方法[1]。例如:
You should set the arguments this way, and should do so before committing the FragmentTransaction
-- however, you could technically do it right after committing the transaction with no ill effects. As others have stated, what you're doing is the suggested newInstance()
factory method for fragments [1]. For example:
private static final String ARG_IS_ARG = "is_arg";
public static CustomFragment newInstance(boolean isArg) {
CustomFragment result = new CustomFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_IS_ARG, isArg);
result.setArguments(args);
return result;
}
[1] http://developer.android.com/reference/android /app/Fragment.html
相关推荐
最新文章