Android Fragment:如何保存实例

时间:2014-04-11 18:46:01

标签: android save fragment instance mapfragment

您好我有一个片段加载地图片段并从服务器获取不同的数据。我想保存我的片段的状态/实例而不破坏和替换它。我知道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();
     }
...
}

因此,有没有人知道如何保存已经在beginnign运行的片段,而不是每次更改片段时都不会替换和销毁它?提前谢谢。

1 个答案:

答案 0 :(得分:1)

取决于你想要对数据和片段做什么:

  1. 是否要使用以前的数据重建片段?
  2. 您想将实例保留在内存中并重新打开吗?
  3. 对于案例1,我建议您使用更永久的数据存储并将数据保存在片段的onStop中。然后,您可以检入onCreateView以查看是否存在数据,并在存在时加载数据。您可以轻松使用sharePref来执行此操作,并且需要3行代码才能读取和写入。如果数据只是位置和一些字符串,我建议这样做。您可以通过在商店数据上使用时间戳来进一步扩展它,如果它太长,您可以忽略以前的数据并再次加载,这对位置数据很有用。

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        super.onCreateView(inflater, container, savedInstanceState);
        ...
    
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        String previousData = prefs.getString("locationData"), null);
        if(previousData != null)
        {
           //Do something with data.
        }
        else {
           try {
              // Loading map and retrives locations from server 
              initilizeMap();
           } catch (Exception e) {
              Log.e("ERROR", "ERROR IN CODE: " + e.toString());
              e.printStackTrace();
           }
        }
    }
    @Override
    public void onStop()
    {
        Log.i(TAG, "onStop");
        super.onStop();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("locationData"), [your data]);
    }
    

    使用onSaveInstanceState保存数据用于配置更改,而不是用于销毁的片段(使用事务替换)。 http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

    对于案例2,您可以在片段上使用show和hide,这样它就不会被销毁,但是您必须修改布局才能拥有多个容器。 http://developer.android.com/reference/android/app/FragmentTransaction.html 除非您的活动旨在同时显示多个片段,否则我建议不要这样做。