您好我有一个片段,它加载地图片段并从服务器获取不同的数据。我想保存我的片段的状态/实例而不破坏和替换它。我确实知道 onSaveInstanceState(Bundle outState) 但我不明白如何在我的情况下应用它(我也读过片段周期)。这是单击菜单项时交换(使用替换)每个片段的活动的代码:
public class Menu extends Activity {
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
// map is here !!
fragment = new TestMap();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.resetTables();
Intent i = new Intent(getApplicationContext(), Login.class);
//Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayo
ut.closeDrawer(mDrawerList);
}
...
}
这是地图的片段:
public class TestMap extends Fargment{
....
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity();
if(inst != null) {
// Remove the view from the parent
((ViewGroup)inst.getParent()).removeView(inst);
// Return it
return inst;
}
else{
final View myFragmentView = inflater.inflate(R.layout.activity_main, container, false);
try {
// Loading map and retrives locations from server
initilizeMap();
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
inst = myFragmentView;
return myFragmentView;
}
}
...
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
...
}
因此,有谁知道如何保存一个已经在开始时运行的片段,而不是每次我更改片段时总是替换和销毁它?先感谢您。