gpt4 book ai didi

java - 将 int 值从 Activity Fragment 传递到另一个 Fragment

转载 作者:行者123 更新时间:2023-12-01 22:59:03 24 4
gpt4 key购买 nike

我需要将一个 int 值从一个 Activity fragment 传递到另一个 fragment 。然后,该数据将被设置为 switch case,这将决定将哪个 Android 布局文件附加到该 fragment 。

这是来自基本 Activity 和设置要​​传递的值的 fragment 上的代码:

Fragment fragment = new otherFragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

顺便说一句,我还尝试将上述代码放在 fragment 的 onCreate 和 onCreateView 方法上,但输出仍然相同。然后在设置 fragment 和 bundle 后,我切换到其他 Activity ,这里是获取和使用 int 值的代码:

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

也尝试过

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

当来自基本 Activity 时,错误是空指针异常,当来自第一个 fragment 时,错误是找不到资源。

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

谢谢。

最佳答案

使用默认构造函数创建 fragment 通常不是正确的方法。下面是一个示例,说明您可以更好地创建 fragment 的新实例并为其传递一个整数。

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

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;
}
}

在您的 Activity 中使用它来创建新 fragment 。

Fragment exampleFragment = ExampleFragment.newInstance(exampleInt);

稍后在您的 fragment 中,使用类似的方法来获取整数。

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

关于java - 将 int 值从 Activity Fragment 传递到另一个 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23603132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com