首页 > 解决方案 > 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>

标签: androidsharedpreferencesdialog-preference

解决方案


您必须实现OnPreferenceChangeListener和/或调用notifyChanged()

除非您提供 that 的代码DialogPreference,否则很难重现该问题。


推荐阅读