我正在使用一個活動來處理多個項目的詳細信息。不能在Backstack中添加/恢復片段sameclass
ActivityA
具有產品列表,當你在任何項目在此列表中單擊,您撥打ActivityB
傳遞產品ID:
ActivityA
:
Intent i = new Intent(this, ProductDetail.class);
i.putExtra("pID", product.getId());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(i);
在onCreate
和onNewIntent
方法,我處理它以這種方式:
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle bundle = new Bundle(); //bundle to send data to the fragment
bundle.putInt("pID", intent.getExtras().getInt("pID"));
ProductDetail details = new ProductDetail();
details.setArguments(bundle);
loadFragment(details);
}
而loadFragment
那m烏斯季增加或恢復到一個特定的片段,如果找到一個具有相同PID標籤:
public void loadFragment(ProductDetail fragment) {
fm = getFragmentManager();
Log.d("TagFrag", "TAG: "+ pID); //can get pID from global variable or extra from fragment
if(fm.findFragmentByTag(pID+"") !=null) {
Log.d("TagFrag", "Already Added");
fm.popBackStack(pID+ "", 0);
} else {
Log.d("TagFrag", "New Added");
ft = fm.beginTransaction();
ft.add(R.id.fragments, fragment, pID+ "");
ft.commit();
fm.executePendingTransactions();
}
這表明,如果它是一個"New Added"
或"Already Added"
,但fm.popBackStack(pID+ "", 0);
只顯示最後添加的片段。
例如:
點擊第1項 - > addFragment - >顯示項目1個詳細
點擊2項 - > addFragment - >顯示項目2個詳細
如果我回到Item列表並再次單擊Item1的行爲是:
Click Item - > fragmentAlreadyAdded - > Display Item Details 爲什麼它不再顯示項目1?
其加入到backStage,entryCount計數,問題是,當我使用popBack返回到第一個片段,所有其他被破壞,我不想這=/ – user2582318
@ user2582318從你的來源來看並不明顯addToBackStack被調用。無論如何,你是否考慮過使用FragmentTransaction的show/hide方法? –
對不起,我忘了添加,我沒有考慮,是否有存儲碎片而不丟失數據,然後顯示/隱藏? – user2582318