现在的位置: 首页 > 综合 > 正文

SharedPreferences封装

2018年04月05日 ⁄ 综合 ⁄ 共 750字 ⁄ 字号 评论关闭

Android五大存储方法之一的SharedPreferences,要保存应用变量值的时候非常有用,这里给出SharedPreferences的封装,方便其他类直接使用

新建SharePreUtil类

<span style="font-size:18px;">public class SharePreUtil {

 SharedPreferences share;
 Context ctx;
 
 public SharePreUtil(Context ctx) {
  super();
  this.ctx = ctx;
  share = ctx.getSharedPreferences("share", 0);//share为存储名称
 }</span>

添加put 和get方法

<span style="font-size:18px;">//存取数据
public void putFirstUse(int firstUse){
     share.edit().putInt("firstUse", firstUse).commit();
    }
 public int getFirstUse(){
     int firstUse = share.getInt("firstUse", 0);
     return firstUse;
    }</span>

这样其他类就可以通过SharePreUtil直接使用SharedPreferences了

<span style="font-size:18px;">SharePreUtil sharePreUtil ;
sharePreUtil = new SharePreUtil(getApplicationContext());//传Context

put、get操作
sharePreUtil.putFirstUse(1);
sharePreUtil.getFristUse();</span>

【上篇】
【下篇】

抱歉!评论已关闭.