creating a DialogPreference from XML

后端 未结 3 1919
旧时难觅i
旧时难觅i 2020-11-30 01:39

I have been attempting to use an android.preference.DialogPreference inflated from XML, but the documentation seems to be missing some essential bits, and I can

3条回答
  •  萌比男神i
    2020-11-30 02:16

    Here is an example of how to use the dialog preference (subclassing as you mentioned).

    package dk.myapp.views;
    
    import android.content.Context;
    import android.preference.DialogPreference;
    import android.util.AttributeSet;
    
    /**
     * The OptionDialogPreference will display a dialog, and will persist the
     * true when pressing the positive button and false
     * otherwise. It will persist to the android:key specified in xml-preference.
     */
    public class OptionDialogPreference extends DialogPreference {
    
        public OptionDialogPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onDialogClosed(boolean positiveResult) {
            super.onDialogClosed(positiveResult);
            persistBoolean(positiveResult);
        }
    
    }
    

    The preferences.xml should contain

    
    

    I have a res/value containing (though the key-name can also be declared explicitly above).

    resetQuests  
    

    My PreferenceActivity does the actual resetting from onPause. Note that onStop may be too late since the onStop will not always be called immediately after pressing back:

    @Override
    public void onPause() {
        SharedPreferences prefs = android.preference.PreferenceManager.
            getDefaultSharedPreferences(getBaseContext());
        if(prefs.getBoolean(
            getResources().getString(R.string.prefKeyResetQuests), false)) {
            // apply reset, and then set the pref-value back to false
        }
    }
    

    Or equivalently since we are still in the PreferenceActivity:

    @Override
    protected void onPause() {
        Preference prefResetQuests =
            findPreference(getResources().getString(R.string.prefKeyResetQuests));
        if(prefResetQuests.getSharedPreferences().
            getBoolean(prefResetQuests.getKey(), false)){
            // apply reset, and then set the pref-value back to false 
        }
    }
    

提交回复
热议问题