本文主要是介绍自定义SharedPreferences的封装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
SpUtil类是对android.content.SharedPreferences的封装,简化了对其的使用。代码如下:
public class SpUtil {private static final String NAME="EY"; //保存文件的名称private static SpUtil instance;public static SpUtil getInstance(){if(instance==null){instance=new SpUtil();}return instance;}private SharedPreferences getSharePerference(Context context){return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);}public String getString(Context context,String key){return SpUtil.getInstance().getSharePerference(context).getString(key, null);}public void setString(Context context,String key,String value){Editor editor=SpUtil.getInstance().getSharePerference(context).edit();editor.putString(key, value);editor.commit();}public boolean getBoolean(Context context,String key){return SpUtil.getInstance().getSharePerference(context).getBoolean(key, false);}public void setBoolean(Context context,String key,boolean value){Editor editor=SpUtil.getInstance().getSharePerference(context).edit();editor.putBoolean(key, value);editor.commit();}public int getInt(Context context,String key){return SpUtil.getInstance().getSharePerference(context).getInt(key, 0);}public void setInt(Context context,String key,int value){Editor editor=SpUtil.getInstance().getSharePerference(context).edit();editor.putInt(key, value);editor.commit();}public Set<String> getStringSet(Context context,String key){return SpUtil.getInstance().getSharePerference(context).getStringSet(key, null);}public void setStringSet(Context context,String key,Set<String> value){Editor editor=SpUtil.getInstance().getSharePerference(context).edit();editor.putStringSet(key, value);editor.commit();}}
注:使用时直接调用即可,例如String类型,调用代码如下:
SpUtil.getInstance().setString(this, "hello", "hello world");
String str=SpUtil.getInstance().getString(this, "hello");
这篇关于自定义SharedPreferences的封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!