Setting Fragment arguments from Activity

百般思念 提交于 2020-01-14 05:50:05

问题


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

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