【发布时间】:2014-07-29 22:27:44
【问题描述】:
今天我遇到了一个很奇怪的情况。
当创建片段的多个实例时,比如说MyFragment,然后我使用FragmentTransaction 替换它们来提交更改,它们都重用了第一个创建实例的相同Bundle。
我使用公共静态方法作为“工厂”来创建MyFragment 的每一个实例:
public class MyFragment extends Fragment {
public static final String FRAG_TAG = "MyFragment";
public static MyFragment newInstance(int myIntArgValue) {
final MyFragment frag = new MyFragment();
final Bundle bundle = new Bundle();
bundle.putInt("myIntArg", myIntArgValue);
frag.setArguments(bundle);
return frag;
}
/** Other relevant methods of the fragment. */
}
然后我将我所有的实例一个接一个地添加到堆栈中:
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
final MyFragment frag = MyFragment.newInstance(position); // position is always a different value
ft.replace(android.R.id.content, frag, MyFragment.FRAG_TAG).addToBackStack("BACK_STACK_TAG"); // I already tried ft.add(...) or ft.remove(this).replace(...);
ft.commit();
因此,对于此片段的 2 个实例,例如 MyFragment.newInstance(1); 和 MyFragment.newInstance(2);
getArguments().getInt("myIntArg") 总是返回 1(第一个创建的实例的值)。
为了解决这个问题,我做了类似的事情:
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
final MyFragment frag = MyFragment.newInstance(position);
final Bundle args = frag.getArguments();
args.remove("myIntArg");
args.putInt("myIntArg", position /** The value I really want to and should be used by the "factory" */);
frag.setArguments(args); // I can to this because the fragment is not yet attached
ft.replace(android.R.id.content, frag, MyFragment.FRAG_TAG).addToBackStack("BACK_STACK_TAG");
ft.commit();
我知道不应该这样做,但它确实有效。 有没有人遇到过这样的事情?我在这里做错了什么?
【问题讨论】:
-
这可能是因为您在声明 Bundle 时使用了 final 吗?你真的检查过你为“myIntArg”设置的值是否总是不同的吗?
-
我已经尝试过不使用
final和相同的东西。是的,我 100% 确定“myIntArg”总是不同的。
标签: android android-fragments bundle fragmenttransaction