【发布时间】:2015-09-13 16:59:30
【问题描述】:
我有一个Activity,在其中我通过替换Fragment 来切换内容。
在这个Activity的onCreate中,我用这个代码设置了第一个Fragment:
fm.beginTransaction().add(R.id.container, new FooFragment(), "f_0").commit();
之后,我想根据Integer(我使用抽屉)将这个Fragment换成另一个Fragment,代码如下:
int position = //I get my index here
Fragment f = fm.findFragmentByTag("f_" + position); //(1)
if (f == null) {
switch (position) {
case 0:
f = new FooFragment();
break;
case 1:
f = new BarFragment();
break;
//Etc...
}
}
//Then I replace the actual Fragment by the new one
fm.beginTransaction()
.replace(R.id.container, f, "f_" + position)
.commit();
我的问题是 (1) 上的代码总是返回 null,所以每次我更改 Fragment 时,它都会创建一个新实例。我希望每个Fragment 类型在任何时候都只有一个实例。
谢谢。
【问题讨论】:
标签: android android-fragments fragmentmanager