我正在使用一个活动和多个片段开发android应用程序。我的应用包含导航抽屉。它的布局包含listview。单击它的项目我使用ft.replace(R.id.my_placehodler, new MyFragment())
动态更改片段并将事务添加到backstack ft.addToBackstack(null)
。当我每次实例化新片段时创建新事务。在我看来,这不是一个好方法。你能给我一些关于正确的片段交易方式的建议吗?
答案 0 :(得分:0)
只需拨打setFragment(FragmentClassObject,false,"fragment");
方法。
public void setFragment(Fragment fragment, boolean backStack, String tag) {
manager = getSupportFragmentManager();
fragmentTransaction = manager.beginTransaction();
if (backStack) {
fragmentTransaction.addToBackStack(tag);
}
fragmentTransaction.replace(R.id.content_frame, fragment, tag);
fragmentTransaction.commit();
}
答案 1 :(得分:0)
如果你想避免为同一个Fragment类实例化多个实例,那就是你希望每个Fragment类都有一个实例,你就可以通过使用标签来识别每个Fragments。
@Override
public void onNavigationDrawerItemSelected(int position) {
String tag = "";
switch (position) {
case 0:
tag = "fragment_0";
break;
case 1:
tag = "fragment_1";
break;
case 2:
tag = "fragment_2";
break;
}
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
// Only in case there is no already instaciated one,
// a new instance will be instanciated.
switch (position) {
case 0:
fragment = new Fragment_class_0();
break;
case 1:
fragment = new Fragment_class_1();
break;
case 2:
fragment = new Fragment_class_2();
break;
}
}
fragmentManager.beginTransaction().replace(R.id.container, fragment, tag).commit();
}