【问题标题】:Retrieve value from Custom DialogPreference and persist value从自定义 DialogPreference 中检索值并保留值
【发布时间】:2013-09-22 22:36:58
【问题描述】:

尝试编写自定义对话框首选项(NumberPickerDialog)。尽管 android 文档详细介绍了这个主题,但我似乎在他们的文档中遗漏了一些基本的构建块。

到目前为止,我所拥有的是一个显示在设置活动中的自定义首选项对话框。我可以单击首选项并填写一个值,然后按确定/取消。

自定义布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editTextNumberPickerValue"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

NumberPickerDialog(正在进行中...):

public class NumberPickerPreference extends DialogPreference {

    public NumberPickerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);

        setDialogLayoutResource(R.layout.numberpicker_dialog);  
        setPositiveButtonText(android.R.string.ok);
        setNegativeButtonText(android.R.string.cancel);
        setDialogIcon(null);
        setPersistent(false);
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        if (positiveResult) {
            Editor editor = getEditor();
            persistInt( value??? );
        }
    }
}

Preference.xml 扩展为:

<com.cleancode.utils.numberpickerpreference.NumberPickerPreference
    android:defaultValue="550"
    android:key="prefLongFlashDuration"
    android:summary="@string/long_flash_duration_summary"
    android:title="@string/long_flash_duration" />

我该怎么做:

  • 居然显示默认值550?
  • 从对话框中检索值?
  • 强制只输入整数值?

我希望有人能对此有所了解,可怜的 Android 文档对这个话题并不友好。

非常感谢。

【问题讨论】:

  • 下面的链接回答了问题stackoverflow.com/a/18601126/1151799
  • 该答案依赖于findIndexOfValue(getValue()) 来检索所选值。该方法在DialogPreference 中不可用,因为它没有意义

标签: java android dialog-preference


【解决方案1】:

在 Google 的文档中,他们对包含 新价值

在此示例中,mNewValue 是一个保存设置当前值的类成员。

因此,您似乎必须依靠成员字段来跟踪包含您的新值的视图。我就是这样解决的

private EditText newPasswordField;

@Override
protected void onBindDialogView(View view) {
    super.onBindDialogView(view);

    newPasswordField = view.findViewById(R.id.new_password_field);
}

所以基本上你重写了一个方法,它可以让你保留对任何元素的引用,该元素包含你的新设置的值

然后你做你已经拥有的:提取新值

@Override
protected void onDialogClosed(boolean positiveResult) {
    Log.i(TAG, "Password dialog closed. Result = " + positiveResult);

    if (positiveResult) {
        persistString(newPasswordField.getText().toString());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多