繁体   English   中英

从自定义DialogPreference检索值并保持值

[英]Retrieve value from Custom DialogPreference and persist value

尝试编写自定义对话框首选项( NumberPickerDialog )。 尽管android文档中有关于此主题的详细信息,但我似乎错过了其文档中的一些基本构建基块。

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

自定义布局:

<?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文档对这个主题不是什么新鲜事。

非常感谢。

他们在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());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM