1

在我更改首选项并提交之前,我是否需要每次都调用 edit SharedPreferences ,或者我可以在 costructor 中只做一次吗?

它是否正确 ?

public class MyPreferencesClass {

    private Context ctx;

    private static SharedPreferences settings;
    private static SharedPreferences.Editor editor;

    // Constructor Class //
    public MyPreferencesClass(Context context) {
        this.ctx = context;
        settings = ctx.getSharedPreferences(CUSTOM_PREFS_NAME, 0);
        editor = settings.edit(); // Called Only once in constructor not not everytime in edit methods
    }

    public static void setSomePref1(Boolean boolValue) {
        // editor = settings.edit(); Not required everytime
        editor.putBoolean(PREFS_1, boolValue);
        editor.commit();            
    }

    public static void setSomePref2(Boolean boolValue) {
        editor.putBoolean(PREFS_2, boolValue);
        editor.commit();            
    }
    ...
}
4

1 回答 1

0

您应该能够使用 SharedPreferences.Editor 实例,只要它有效,因此无需每次都调用 SharedPreferences#edit() 。

于 2012-04-06T07:39:00.683 回答