带有 bundle 的 Android 奇怪行为

标签 android bundle

我正在使用 bundle 将数据从 Activity 发送到 Fragment。

这是 Activity 中的代码:

 Bundle extras1 = new Bundle();
    extras1.putString("productId", productId);
    extras1.putString("ddsId", id1);

 frag1.setArguments(extras1);

 getSupportFragmentManager().beginTransaction().add(frame1.getId(), frag1, "fragment_grandchild1" + fragCount).commit();

现在,当我在调试中运行我的项目并将鼠标悬停在 exras1 上时,我可以看到 productId 和 ddsId 都确定了它们的值。

然后是我 fragment 中的代码:

    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null) {
        productId = extras.getString("productId");
        ddsId = extras.getString("ddsId");
     }

现在发生的奇怪事情是它只接收 productId?

当我调试并将鼠标悬停在 extras 上时,它只有 productId 而没有 ddsID。 怎么会这样?

编辑:

我发现了它在做什么。出于某种原因,它将 Activity 类收到的包发送给我的 fragment 。不是我指定的那个。

我该如何改变它?

最佳答案

您正在阅读 Activity 的额外内容。尝试以下操作:

Bundle extras1 = new Bundle();
extras1.putString("productId", productId);
extras1.putString("ddsId", id1);

Fragment fg = new Fragment();
fg.setArguments(extras1);

然后在你的 fragment 中:

Bundle extras = getArguments();
if (extras != null) {
    productId = extras.getString("productId");
    ddsId = extras.getString("ddsId");
}

使用:

Bundle extras = getArguments();

而不是:

Bundle extras = getActivity().getIntent().getExtras();

提示(希望对您有所帮助)

我在许多代码中看到,如果您没有很多额外功能,通常的做法是像这样在 fragment 中创建一个静态方法。

public static YourFragment newInstance(String extra1, int extra2) {
    Fragment fg = new YourFragment();

    Bundle args = new Bundle();
    args.putString("extra1TagId", extra1);
    args.putInt("extra2TagId", extra2);

    fg.setArguments(args);

    return fg;
}

关于带有 bundle 的 Android 奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368314/

相关文章:

ios - 如何从iOS静态库访问Bundle

android - 以高分辨率保存 Canvas 图像

ios - 无法编辑 bundle 标识符

android - savedInstanceState.getInt 中的第二个参数是什么?

android - 什么是App多行文字共享 Intent

java - 我无法在我的 OSGI 包中加载 HelpGUI

ruby-on-rails - bundle 执行 rake Assets :precompile

java - 设置列表首选项后,为什么我的应用不会更改为深色模式 (Android Q)?

android - 如何在整个recyclerview行上单击以选中复选框

Android垂直缩放图像