Android Fragment:如何保存实例 [英] Android Fragment: how to save an instance

查看:80
本文介绍了Android Fragment:如何保存实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨,我有一个片段,它加载地图片段并从服务器获取不同的数据。我想保存片段的状态/实例,而不破坏和替换它。我确实知道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();
     }
...
}
因此,有谁知道如何保存一开始已经运行的Keep a片段,而不是每次我更改片段时总是替换和销毁它?提前谢谢您。

推荐答案

取决于您要如何处理数据和片段:

  1. 是否要使用以前的数据重建碎片?
  2. 是否要将该实例保留在内存中并重新打开它?

对于第一种情况,我建议您使用更持久的数据存储,并将数据保存在片段的onStop中。然后,您可以签入onCreateView以查看数据是否存在,如果存在,则加载回数据。您可以很容易地使用SharPref来完成这项工作,并且只需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)

对于第二种情况,您只需在片段上使用show和Hide,这样它就不会被销毁,但随后您必须修改布局以拥有多个容器。http://developer.android.com/reference/android/app/FragmentTransaction.html 除非您的活动设计为同时显示多个片段,否则我不建议使用此方法。

这篇关于Android Fragment:如何保存实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆