android - DialogPreference 没有在我期望的时候保存首选项?
问题描述
我已经编写了一个基本的标准 DialogPreference 工作正常,除了它没有在我期望的时候将首选项保存到默认的共享首选项。
1) 打开应用程序,主活动显示默认共享首选项中的 foo 值 = 1
2)进入设置
3)点击 foo 设置打开我的 DialogPreference 并显示 value = 1
4) 输入值 3
5) 使用 Ok 按钮关闭我的 DialogPreference
***** 默认共享首选项 foo 现在应该是 3
6)点击 foo 设置打开我的 DialogPreference 并显示 value = 1
***** 所以我的 DialogPreference 没有将首选项保存到默认共享首选项?
7) 取消对话框
8) 返回主活动,显示默认共享首选项 = 3 中的 foo 值
***** 所以我的 DialogPreference 确实将首选项保存到默认共享首选项
9) 进入设置
10)点击 foo 设置打开我的 DialogPreference 并显示值为 3
为什么在步骤 (6) 中默认共享首选项的值不是 foo = 3?
当流程从设置列表返回到主活动时,似乎仅将首选项保存到默认共享首选项,这与将首选项保存在 DialogPreference 的 onDialogClosed 方法中是反直觉的。
我的对话首选项
public class MyDialogPreference extends DialogPreference
{
private static final String DEFAULT_VALUE = "0";
private String value = DEFAULT_VALUE;
private EditText editText;
public MyDialogPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
setDialogLayoutResource(R.layout.constrained_integer_preference);
}
@Override
public void onBindDialogView(View view)
{
super.onBindDialogView(view);
editText = (EditText) view.findViewById(R.id.edit);
editText.setText("" + value);
}
@Override
protected void onDialogClosed(boolean positiveResult)
{
if (positiveResult)
{
persistString(editText.getText().toString());
}
super.onDialogClosed(positiveResult);
}
@Override
protected Object onGetDefaultValue(TypedArray typedArray, int index)
{
return typedArray.getString(index);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue)
{
if (restorePersistedValue)
{
value = getPersistedString(DEFAULT_VALUE);
}
else
{
value = (String) defaultValue;
if (shouldPersist())
{
persistString(value);
}
}
}
}
编辑:所以看来我使用 DialogPreference 处理的首选项没有键,这导致了所有问题。但是我已经在preferences.xml 文件中为这个DialogPreference 指定了键。我已经尝试了一切来强制识别密钥,但没有任何效果。
谁能告诉我如何让 DialogPreference 从preferences.xml 文件中接收 android:key 来工作?
首选项.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<org.mycompany.myproject.MyDialogPreference
android:defaultValue="11"
android:dialogLayout="@layout/my_preference"
android:inputType="number"
android:key="MY_KEY"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="summary"
android:title="My Preference" />
</PreferenceScreen>
解决方案
您必须实现OnPreferenceChangeListener和/或调用notifyChanged()。
除非您提供 that 的代码DialogPreference
,否则很难重现该问题。
推荐阅读
- spring - Spring - 提交表单后如何让页面刷新?
- c# - 在 .NET Core Web 应用程序中测试路由
- python - 为什么使用自己的分类训练 Keras NN 时损失函数不会减少?
- angular - 离子 4:ngOnInit 与 ionViewWillEnter
- python - 如何使用字典数据制作子图?
- python - TensorFlow Serving 将数据作为 b64 而不是 Numpy Array 发送
- python - 无符号字符数组问题
- c++ - 如何避免文件变量成为 OpenMP 中的竞争条件(离散元方法模拟)
- php - 将命令行 cURL 转换为 PHP cURL(带身份验证)
- laravel - Laravel 如何测试 _Constructor