转载请注明,原文地址:http://blog.csdn.net/liu17ezlyy
偶尔看到一些老外的代码,总感觉他们写太好了,很赞。我技术一般,没有这么大的能耐,只能简单优化一下我认为能缩减的代码,不要一个方法复制来,复制去的。下面优化了
SharedPreferences和Toast的使用。
1:SharedPreferences是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。
我把常用到的取出String类型数据,int类型数据和保存string类型数据,int类型数据,一共四个方法,简单的写到了一起。
- /**
- * @author Liu Chuanyang
- * address:JiNan ShanDong
- * QQ:516542477 welcome communication
- * 2013-1-25下午5:09:22
- */
- package com.ly.util;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.view.Gravity;
- import android.widget.Toast;
- /**
- * @author Administrator
- *
- */
- public class myConfig {
- /**
- *
- * @param mContext 上下文,来区别哪一个activity调用的
- * @param whichSp 使用的SharedPreferences的名字
- * @param field SharedPreferences的哪一个字段
- * @return
- */
- //取出whichSp中field字段对应的string类型的值
- public static String getSharePreStr(Context mContext,String whichSp,String field){
- SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0);
- String s=sp.getString(field,"0");//如果该字段没对应值,则取出字符串0
- return s;
- }
- //取出whichSp中field字段对应的int类型的值
- public static int getSharePreInt(Context mContext,String whichSp,String field){
- SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0);
- int i=sp.getInt(field,0);//如果该字段没对应值,则取出0
- return i;
- }
- //保存string类型的value到whichSp中的field字段
- public static void putSharePre(Context mContext,String whichSp,String field,String value){
- SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0);
- sp.edit().putString(field, value).commit();
- }
- //保存int类型的value到whichSp中的field字段
- public static void putSharePre(Context mContext,String whichSp,String field,int value){
- SharedPreferences sp=(SharedPreferences) mContext.getSharedPreferences(whichSp, 0);
- sp.edit().putInt(field, value).commit();
- }
- /**
- * Toast的封装
- * @param mContext 上下文,来区别哪一个activity调用的
- * @param msg 你希望显示的值。
- */
- public static void showMsg(Context mContext,String msg) {
- Toast toast=new Toast(mContext);
- toast=Toast.makeText(mContext,msg, 300);
- toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);//设置居中
- toast.show();//显示,(缺了这句不显示)
- }
- }
其实就是写成了方法,使用的直接调用方法就行了。
例如使用其中的getSharePreStr和showMsg方法
- String s=myConfig.getSharePreStr(MainActivity.this, "sp", "sp");
- myConfig.showMsg(MainActivity.this, s);
最后放上工程