我使用android支持庫,我有3個片段的活動。 ,我有一個問題:替換片段的刪除其他片段Android:替換片段刪除其他片段
我的活動:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add 3 fragments:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container1, new A(), A.class.getCanonicalName())
.commit();
getFragmentManager().beginTransaction()
.add(R.id.container2, new B(), B.class.getCanonicalName())
.commit();
getFragmentManager().beginTransaction()
.add(R.id.container3, new C(), C.class.getCanonicalName())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.test) {
Fragment fragment = getFragmentManager().
findFragmentByTag(A.class.getCanonicalName());
if (fragment == null)
fragment = new A();
// Replace fragment A again
getFragmentManager()
.beginTransaction()
.replace(R.id.container1, fragment, fragment.getClass().getCanonicalName())
.commit();
// After this fragment B disappears
return true;
}
return super.onOptionsItemSelected(item);
}
}
我使用findFragmentByTag避免內存泄漏。 你能幫我嗎?
嘗試增加這片段的交易,之前提交 '//添加本次交易後堆 .addToBackStack()' –
不知道你的問題是清楚的,因爲你做.replace這樣按預期的方式取代了以往的片段。現在@IonutNegru說,如果問題是你不能倒退,那麼使用addToBackStack,但問題並不清楚。 – HpTerm
@HpTerm也是對的,你應該使用add來避免替換當前片段。我錯過了那一個。 您可以查看碎片的官方文檔。你的情況也有一些例子。 –