美文网首页
【Android】一个有用的工具类

【Android】一个有用的工具类

作者: 码上新视界 | 来源:发表于2015-02-28 23:06 被阅读240次
    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);
    }
}
 }

相关文章

网友评论

      本文标题:【Android】一个有用的工具类

      本文链接:https://www.haomeiwen.com/subject/aeopxttx.html