封装SharedPreferences和Toast
今天做DEMO需要经常用到SharedPreferences和Toast,于是很自然的想到了将它们封装成方法,到时候直接调用。
我像常规的实现方法那样写:
SharedPreferences sp_login=getSharedPreferences(sp_name, MODE_PRIVATE); Editor editor=sp_login.edit(); editor.putString(key, content); editor.commit()
但是在做的时候SharedPreferences的MODE始终表示未定义,后来我把mode换成0,getSharedPreferences又报错,后来才知道要确定context。
在网上搜索到一篇封装SharedPreferences和Toast的文章:
http://blog.csdn.net/liu17ezlyy/article/details/8542944即下面这个例子:
1 package com.ly.util; 2 3 import android.content.Context; 4 import android.content.SharedPreferences; 5 import android.view.Gravity; 6 import android.widget.Toast; 7 8 /** 9 * @author Administrator 10 * 11 */ 12 public class myConfig { 13 /** 14 * 15 * @param mContext 上下文,来区别哪一个activity调用的 16 * @param whichSp 使用的SharedPreferences的名字 17 * @param field SharedPreferences的哪一个字段 18 * @return 19 */ 20 //取出whichSp中field字段对应的string类型的值 21 public static String getSharePreStr(Context mContext,String whichSp,String field){ 22 SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0); 23 String s=sp.getString(field,"0");//如果该字段没对应值,则取出字符串0 24 return s; 25 } 26 //取出whichSp中field字段对应的int类型的值 27 public static int getSharePreInt(Context mContext,String whichSp,String field){ 28 SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0); 29 int i=sp.getInt(field,0);//如果该字段没对应值,则取出0 30 return i; 31 } 32 //保存string类型的value到whichSp中的field字段 33 public static void putSharePre(Context mContext,String whichSp,String field,String value){ 34 SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0); 35 sp.edit().putString(field, value).commit(); 36 } 37 //保存int类型的value到whichSp中的field字段 38 public static void putSharePre(Context mContext,String whichSp,String field,int value){ 39 SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0); 40 sp.edit().putInt(field, value).commit(); 41 } 42 43 /** 44 * Toast的封装 45 * @param mContext 上下文,来区别哪一个activity调用的 46 * @param msg 你希望显示的值。 47 */ 48 public static void showMsg(Context mContext,String msg) { 49 Toast toast=new Toast(mContext); 50 toast=Toast.makeText(mContext,msg, 300); 51 toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);//设置居中 52 toast.show();//显示,(缺了这句不显示) 53 } 54 }
作者:af74776
文章出处:http://www.cnblogs.com/scetopcsa/
欢迎关注微信公众号:yilu_yiyou(一路一游),一个不仅仅是代码的世界!
如果文中有什么错误,欢迎指出。以免更多的人被误导。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
文章出处:http://www.cnblogs.com/scetopcsa/
欢迎关注微信公众号:yilu_yiyou(一路一游),一个不仅仅是代码的世界!
如果文中有什么错误,欢迎指出。以免更多的人被误导。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号