如何创建具有多个字段的单个首选项?

How to create a single preference with multiple fields?

我的应用程序设置中有一个 "change password",我希望用户能够输入 3 个文本字段(当前密码、新密码、重复密码),然后只需单击确定按钮即可保存设置。但问题是我找不到(或无法创建)任何可以显示多个项目的首选项(这里是 3 EditTextPreferences)。

下面的代码在点击编辑时只显示一个文本框。

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <EditTextPreference
        android:capitalize="none"
        android:password="true"
        android:defaultValue=""
        android:inputType="textCapWords"
        android:key="example_text"
        android:maxLines="1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="@string/pref_default_current_password" />

</PreferenceScreen>

我正在寻找类似的东西:

<Group>
        <EditTextPreference
            android:capitalize="none"
            android:password="true"
            android:defaultValue=""
            android:inputType="textCapWords"
            android:key="example_text"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="@string/pref_default_current_password" />

        <EditTextPreference
            android:capitalize="none"
            android:password="true"
            android:defaultValue=""
            android:inputType="textCapWords"
            android:key="example_text"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="@string/pref_default_new_password" />

        <EditTextPreference
            android:capitalize="none"
            android:password="true"
            android:defaultValue=""
            android:inputType="textCapWords"
            android:key="example_text"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="@string/pref_default_repeat_password" />
</Group>

您需要按提交按钮按顺序。

Editor editor = sharedpreferences.edit();

editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3"); 
editor.commit();

或者最好创建共享首选项实用程序以避免此类样板。

您需要创建自定义 DialogPreference。在我看来,您的方法有缺陷,您只希望将一个偏好值存储在 SharedPreferences.

创建一个 class 扩展 DialogPreference,return 您的膨胀视图 onCreateDialogView(),并在单击肯定按钮时添加一些逻辑。你管理它是一个片段或 activity class,只是扩展 DialogPreference:

public class CustomPreference extends DialogPreference {

    EditText first;
    EditText second;
    EditText third;

    protected View onCreateDialogView() {
        View v = LayoutInflater.from(getContext()).inflate(R.layout.three_edit_texts, null);
        first = v.findViewById(...);
        second = v.findViewById(...);
        third = v.findViewById(...);
        return v;
    }

}

然后在 XML 中添加一个:

<com.your.package.CustomPreference />