从设置片段活动参数 [英] Setting Fragment arguments from Activity

查看:111
本文介绍了从设置片段活动参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否调用 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

这篇关于从设置片段活动参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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