3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
以XML格式編碼的片段無(wú)法替換。如果你需要用另一個(gè)片段替換片段,你應(yīng)該首先動(dòng)態(tài)添加它們。
注意:R.id.fragment_container是您將片段帶到的活動(dòng)中所選擇的布局或容器。
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
我已經(jīng)用完美的方法來(lái)管理片段 替換和生命周期。
它只用一個(gè)新片段替換當(dāng)前片段,如果它不相同并且它不在backstack中(在這種情況下它將彈出它)。
它包含幾個(gè)選項(xiàng),就好像您希望將片段保存在backstack中一樣。
=> 見這里的要點(diǎn)
使用此活動(dòng)和單個(gè)活動(dòng),您可能希望將其添加到您的活動(dòng)中:
@Overridepublic void onBackPressed() { int fragments = getSupportFragmentManager().getBackStackEntryCount(); if (fragments == 1) { finish(); return; } super.onBackPressed();}
添加回答
舉報(bào)