SharedPreferences一般是用于系统设置数据的存储,在项目中我用在了Fragment返回前一个Fragment,保证前一个Fragment数据不丢失!
SharedPreferences基本存取
存数据
SharedPreferences.Editor 一个类似map的东西,生成键值对,存入xml中。
- 我这个是写在Fragment中,所以要getActivity();
- 你也可以写个静态方法在MainActivity中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public void inStore(){ SharedPreferences mySharedPreferences= getActivity().getSharedPreferences("bodyinfo", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putString("Age", dis_tv1.getText().toString()); editor.putString("Height", dis_tv2.getText().toString()); editor.putString("Weight", dis_tv3.getText().toString()); editor.commit(); Toast.makeText(getActivity(), "数据成功写入SharedPreferences!" , Toast.LENGTH_LONG).show(); }
|
取数据
写入控件中
1 2 3 4 5 6 7 8 9 10 11 12 13
|
public void outStore(){ SharedPreferences sharedPreferences= getActivity().getSharedPreferences("bodyinfo", Activity.MODE_PRIVATE); dis_tv1.setText(sharedPreferences.getString("Age", "")); dis_tv2.setText(sharedPreferences.getString("Height", "")); dis_tv3.setText(sharedPreferences.getString("Weight", "")); Toast.makeText(getActivity(), "读取数据如下成功", Toast.LENGTH_LONG).show(); }
|
Fragment跳转Fragment数据不丢失
- 跳转前A将数据存储到SharedPreferences中
- 跳转B后返回时候加载
通过A设置全局变量mStack,在每次跳转时候,mStack++;
当然你会问mStack在transaction.replace()方法时候移除了,在加载又是初始值。看下一条
- 为了保存Fragment中的变量,一般会重写onSaveInstanceState(Bundle outState)和 onCreate(Bundle savedInstanceState) 。一个存一个取
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("level", mStackLevel); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
if (savedInstanceState != null) { mStackLevel = savedInstanceState.getInt("level"); } }
|
- 最后,在onCreateView重新加载视图
1 2 3 4 5 6 7
| @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ if(mStackLevel != 0){ outStore(); } }
|