2013-08-21 41 views
1

我正在使用捆綁包將數據從活動發送到片段。Android與包的奇怪行爲

下面是活動中的代碼:

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是前一定要與自己的價值觀。

然後EHRE是我在我的代碼片段:

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

現在正在發生奇怪的事情是,它只能接收的productId?

當我調試並將鼠標懸停在extras上時,它只有productId而不是ddsID。 這怎麼會發生?

編輯:

我已經發現它在做什麼。出於某種原因,它會將我的片段發送給活動班級收到的包。不是我指定的那個。

我該如何去改變它?

回答

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(); 

不是:

​​

TIP(希望它他lps)

我在很多代碼中看到如果你沒有很多額外的東西,那麼在這樣的片段中創建一個靜態方法是很常見的做法。

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

哦,我明白了。我正確設置它們。我只是訪問活動附加組件而不是碎片附加組件。你的冠軍,它的作品, – Zapnologica

+0

我編輯我的答案與建議。 – Juangcg