【Android】一个有用的工具类

    import android.content.Context;
    import android.content.SharedPreferences;
    
    import java.util.Map;
    import java.util.Set;

    /**
     * @author Alejandro Rodriguez <https://github.com/Alexrs95/Prefs>
     *         <p/>
     *         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<String> 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<String> getStringSet(String key, Set<String> defValue) {
    return preferences.getStringSet(key, defValue);
}

public Map<String, ?> 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);
    }
}
 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容