android工具类有什么用,【Android】一个有用的工具类

这篇文章介绍了一个名为Prefs的Android偏好设置封装类,提供了一系列便捷的方法如put和get操作,简化了SharedPreferences的使用。它允许开发者以更流畅的方式管理应用设置,提升开发效率。
摘要由CSDN通过智能技术生成

import android.content.Context;

import android.content.SharedPreferences;

import java.util.Map;

import java.util.Set;

/**

* @author Alejandro Rodriguez

*

* Wrapper over the Android Preferences which provides a fluid syntax

*/

public class Prefs {

private static final String TAG = "Prefs";

static Prefs singleton = null;

static SharedPreferences preferences;

static SharedPreferences.Editor editor;

Prefs(Context context) {

preferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);

editor = preferences.edit();

}

public static Prefs with(Context context) {

if (singleton == null) {

singleton = new Builder(context).build();

}

return singleton;

}

public void save(String key, boolean value) {

editor.putBoolean(key, value).apply();

}

public void save(String key, String value) {

editor.putString(key, value).apply();

}

public void save(String key, int value) {

editor.putInt(key, value).apply();

}

public void save(String key, float value) {

editor.putFloat(key, value).apply();

}

public void save(String key, long value) {

editor.putLong(key, value).apply();

}

public void save(String key, Set value) {

editor.putStringSet(key, value).apply();

}

public boolean getBoolean(String key, boolean defValue) {

return preferences.getBoolean(key, defValue);

}

public String getString(String key, String defValue) {

return preferences.getString(key, defValue);

}

public int getInt(String key, int defValue) {

return preferences.getInt(key, defValue);

}

public float getFloat(String key, float defValue) {

return preferences.getFloat(key, defValue);

}

public long getLong(String key, long defValue) {

return preferences.getLong(key, defValue);

}

public Set getStringSet(String key, Set defValue) {

return preferences.getStringSet(key, defValue);

}

public Map getAll() {

return preferences.getAll();

}

public void remove(String key) {

editor.remove(key).apply();

}

private static class Builder {

private final Context context;

public Builder(Context context) {

if (context == null) {

throw new IllegalArgumentException("Context must not be null.");

}

this.context = context.getApplicationContext();

}

/**

* Method that creates an instance of Prefs

*

* @return an instance of Prefs

*/

public Prefs build() {

return new Prefs(context);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值