【Android】一个有用的工具类

    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); } } }

你可能感兴趣的:(【Android】一个有用的工具类)