编写新的DialogPreference类的简洁方法?
我正在通过扩展DialogPreference类在Android中编写一些自定义首选项对话框。 不过,由于看起来有很多行为需要testing,所以我需要关注一下锅炉板代码的数量。
例如,这个数字首选项对话框的例子是相当典型的: http : //svn.jimblackler.net/jimblackler/trunk/workspace/NewsWidget/src/net/jimblackler/newswidget/NumberPreference.java
特别是, onSave() / RestoreInstanceState()方法和“SavedState类”部分,这些对象的当前更改保留在方向更改上是非常繁琐和复杂的。
有没有人有更简洁的方式编写DialogPreference类的任何提示?
最低限度是:
-
MyCustomDialogPreference(Context context, AttributeSet attrs)构造函数。- 不要忘记调用
super(context, attrs)。 - 调用
setPersistent(false)向超级首选项类指示您自己保留首选项值。 - 如果要从资源中
setDialogLayoutResource(int dialogLayoutResId)对话框布局,则还要调用setDialogLayoutResource(int dialogLayoutResId)。
- 不要忘记调用
-
onBindDialogView(View view)– 使用您的首选项的值更新视图。- 不要忘记调用
super.onBindDialogView(view)。
- 不要忘记调用
-
onDialogClosed(boolean positiveResult)– 如果positiveResult为true,则将视图中的值保存到SharedPreferences中。- 不要忘记调用
super.onDialogClosed(positiveResult)。
- 不要忘记调用
这是最低限度的,它假设:
- 您的自定义DialogPreferencepipe理单个首选项键/值对。
- 你有责任坚持优先价值。
- 您正在从资源膨胀对话框面板布局。
现在有一些额外的select:
(a)如果要以编程方式创build对话框布局,则还需要在构造函数中实现onCreateDialogView()而不是调用setDialogLayoutResource() 。
(b)如果你的首选项只支持一个键/值对,那么你可以使用助手保存方法persistBoolean(boolean), persistFloat(float), persistInt(int), persistLong(long), persistString(String)在onDialogClosed()中更改的优先值。 否则,您需要使用getEditor()方法,如下所示:
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)如果你打算提供一个膨胀的xml的默认值,那么你还需要实现onGetDefaultValue(TypedArray a, int index)方法。
@理查德·牛顿,我知道你问这个问题已经有一个月了。 我希望你仍然可以使用它。