问题
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);
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?
回答1:
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()
).
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
回答2:
There should be no problem. I am working on a project right now that uses this exact format in several spots.
This format is in the Android Developers example project as well (find 'Arguments'):
http://developer.android.com/reference/android/app/Fragment.html
回答3:
Similar to what @kcoppock said, in most cases you will be instantiating the Fragment
on the UI thread, and then Android queues up the arguments you pass to the Fragment
on the UI thread as well. There's no race conditions because the operations take place at different times on the same thread.
For more information, check out this blog post on Activities and Fragments: http://www.zerotohired.com/2015/02/passing-data-between-activities-and-fragments-in-android.
来源:https://stackoverflow.com/questions/24814389/setting-fragment-arguments-from-activity