片段getArgs()中的bundle是否与通过setArgs()传递的对象相同?

时间:2014-06-14 23:50:00

标签: android android-fragments android-activity bundle

如果我将片段myfragment的参数设置为Bundle mybundle,我保证如果我稍后改变mybundle的内容,myfragment对getArguments()的调用将与mybundle的内容一致吗?

mybundle.putString("background", "red");
myfragment.setArguments(mybundle);

...稍后......

mybundle.putString("background", "orange");
myfragment.createLayoutFromBundle(myfragment.getArguments());

2 个答案:

答案 0 :(得分:1)

是。检查source code for the Fragment class。捆绑包不会被复制或任何东西,只是按原样返回。

    public void setArguments(Bundle args) {
        if (mIndex >= 0) {
            throw new IllegalStateException("Fragment already active");
        }
        mArguments = args;
    }

/**
* Return the arguments supplied when the fragment was instantiated,
* if any.
*/
    final public Bundle getArguments() {
        return mArguments;
    }

答案 1 :(得分:0)

参数Bundle是片段保存的实例状态的一部分。如果片段被销毁并重新创建,则新创建的片段将具有与原始Bundle具有相同内容的参数Bundle。但是,Bundle对象可能不同。

在以下情况下最容易看到:

  • 用户位于您的片段中,其中包含Bundle
  • 用户按HOME
  • 您的流程已终止(您可以通过DDMS进行测试)
  • 用户通过recent-tasks list
  • 返回您的片段

Bundle中的数据与之前一样,但Bundle对象将是新创建的。