将一个int值从Activity Fragment传递给另一个Fragment

时间:2014-05-12 07:17:38

标签: java android android-fragments

我需要将一个活动片段的int值传递给另一个片段。然后将此数据设置为切换案例,该案例将决定哪个Android布局文件将附加到片段。

这是基本活动和设置要​​传递的值的片段的代码:

Fragment fragment = new otherFragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
顺便说一句,我也尝试将上面的代码放在片段的onCreate和onCreateView方法上,但仍然是相同的输出。然后在设置片段和包之后,我切换到另一个活动,这里是将获取并使用int值的代码:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);

也尝试了

savedInstanceState = this.getArguments();
int type = savedInstanceState.getInt(key, defaultValue);

从基本活动开始,错误是空指针异常,而当从第一个片段开始,错误是找不到资源。

05-12 14:50:47.732: E/ERRORSKI(814): java.lang.NullPointerException
05-12 14:41:38.542: E/ERRORSKI(798): android.content.res.Resources$NotFoundException: String resource ID #0x1

谢谢。

1 个答案:

答案 0 :(得分:3)

使用默认构造函数创建片段通常不是最佳选择。 下面是一个示例,说明您可以更好地创建片段的新实例并使用它传递整数。

将此代码放入将要创建的片段中。

public class ExampleFragment {
    public static ExampleFragment newInstance(int exampleInt) {
        ExampleFragment fragment = new ExampleFragment();

        Bundle args = new Bundle();
        args.putInt("exampleInt", exampleInt);
        fragment.setArguments(args);

        return fragment;
    }
}

在您的活动中使用它来创建新片段。

Fragment exampleFragment = ExampleFragment.newInstance(exampleInt);

稍后在你的片段中,使用类似的东西来获取整数。

getArguments().getInt("exampleInt", -1);