比较简单直接贴代码了
SharedPreferences工具类
package abc.lcs.healthlife.utils;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class UserHistoryOption {
Context context;
// 单例模式,防止重复创建对象
private UserHistoryOption(Context context) {
this.context=context;
privatepreferences =context.getSharedPreferences("userhtistory",Context.MODE_PRIVATE);
edit= privatepreferences.edit();
}
private static UserHistoryOption userHistoryOption;
public static UserHistoryOption getInstance(Context context){
if (userHistoryOption==null){
userHistoryOption=new UserHistoryOption(context);
}
return userHistoryOption;
}
public boolean getBol(String key){
return privatepreferences.getBoolean(key,false);
}
public String getStr(String key){
return privatepreferences.getString(key,null);
}
/**
* 写单条字符
* @param key 键
* @param value 值
*/
public void writeStr(String key,String value){
edit.putString(key,value);
edit.commit();
}
/**
* 写字符set集合
* @param key 键
* @param value 值
*/
public void writeSetStr(String key,Set<String> value){
edit.putStringSet(key,value);
edit.commit();
}
public SharedPreferences.Editor edit ;
public final SharedPreferences privatepreferences;
public void writeData(HashMap<String,Object> datas){
// edit.clear();
for (String key:datas.keySet()){
Object valu=datas.get(key);
if (valu instanceof String){
edit.putString(key,String.valueOf(valu));
} else if (valu instanceof Integer){
edit.putInt(key,(Integer) valu);
}else if (valu instanceof Boolean){
edit.putBoolean(key,(boolean)valu);
}else if (valu instanceof Float){
edit.putFloat(key, (Float) valu);
}else if (valu instanceof Long){
edit.putLong(key, (Long) valu);
}else edit.putStringSet(key, (Set<String>) valu);
}
// *清空文件用
// edit.clear();
//edit一起执行 相当于commit()
edit.apply();
}
/**读取Set<String>集合 返回迭代器*/
public Iterator<String> readSetStr(@NonNull String key){
Set<String > stringSet= privatepreferences.getStringSet(key,null);
if (stringSet==null){
return null;
}
//返回迭代器
return stringSet.iterator();
}
}
Toast工具类
package abc.lcs.healthlife.utils;
import android.content.Context;
import android.widget.Toast;
public class ToastUtil {
private static Toast shortToast=null;
public static void showShort(Context context, String info) {
if (shortToast==null){
shortToast=Toast.makeText(context, info, Toast.LENGTH_SHORT);
}else {
shortToast.setText(info);
}
shortToast.show();
}
private static Toast longToast=null;
public static void showLong(Context context, String info) {
if (longToast==null){
longToast=Toast.makeText(context, info, Toast.LENGTH_LONG);
}else {
longToast.setText(info);
}
longToast.show();
}
}