1

アクティビティからフラグメントにデータを送信するためにバンドルを使用しています。

アクティビティのコードは次のとおりです。

 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 の両方が値に確実に一致することがわかります。

そして、私のフラグメントのコードは次のとおりです。

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

今起こっている奇妙なことは、それがproductIdだけを受け取っているということですか?

デバッグしてエクストラにカーソルを合わせると、productId のみが表示され、ddsID は表示されません。これはどのように起こっているのでしょうか?

編集:

私はそれが何をしているのかを発見しました。何らかの理由で、アクティビティ クラスが受信したバンドルをフラグメントに送信します。私が指定しているものではありません。

どうすればそれを変更できますか?

4

1 に答える 1

1

アクティビティのエキストラを読んでいます。次のことを試してください。

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

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

次に、フラグメントで:

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

使用する:

Bundle extras = getArguments();

それよりも:

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

ヒント(お役に立てば幸いです)

多くのコードで、エクストラがあまりない場合、このようにフラグメントに静的メソッドを作成するのが一般的な方法であることがわかりました。

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;
}
于 2013-08-21T21:57:21.113 に答える