The bare minimum is:
MyCustomDialogPreference(Context context, AttributeSet attrs)
constructor.
- Don't forget to call
super(context, attrs)
.
- Call
setPersistent(false)
to indicate to the super Preference class that you persist the preference value on your own.
- If you want to inflate the dialog panel layout from a resource, then also call
setDialogLayoutResource(int dialogLayoutResId)
.
onBindDialogView(View view)
- update the view with the value(s) of your preference.
- Don't forget to call
super.onBindDialogView(view)
.
onDialogClosed(boolean positiveResult)
- if positiveResult is true then persist the value(s) from your view to the SharedPreferences.
- Don't forget to call
super.onDialogClosed(positiveResult)
.
This was the bare minimum, and it assumes that:
- Your custom DialogPreference manages a single preference key/value pair.
- You are responsible for persisting the preference value.
- You are inflating the dialog panel layout from a resource.
Now for some additional options:
(a) If you want to create the dialog panel layout programmatically, then implement also onCreateDialogView()
instead of calling setDialogLayoutResource()
in the constructor.
(b) If your preference supports only a single key/value pair, then you can use the helper save methods persistBoolean(boolean), persistFloat(float), persistInt(int), persistLong(long), persistString(String)
when you persist the changed preference value in onDialogClosed(). Otherwise, you need to use the getEditor()
method, like so:
private MyCustomView myView;
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
// the view was created by my custom onCreateDialogView()
myView = (MyCustomView)view;
SharedPreferences sharedPreferences = getSharedPreferences();
myView.setValue1(sharedPreferences.getString(myKey1, myDefaultValue1));
myView.setValue2(sharedPreferences.getString(myKey2, myDefaultValue2));
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
Editor editor = getEditor();
editor.putString(myKey1, myView.getValue1());
editor.putString(myKey2, myView.getValue2());
editor.commit();
}
}
(c) If you plan to supply default values from an inflated xml, then you need to implement also the onGetDefaultValue(TypedArray a, int index)
method.
@RichardNewton, I know that a month has passed since you asked the question. I hope you can still use it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…