简体   繁体   English

如何在PreferenceFragment之外修改Androidx Preference数据?

[英]How to modify Androidx Preference data outside of PreferenceFragment?

I am trying to implement a custom Radio-style Preference where the user can click an option which is then assigned as the new value of the Preference : 我正在尝试实现一个自定义的无线电样式Preference ,用户可以单击一个选项,然后将该Preference指定为首选项的新值:

在此输入图像描述

Here is my layout: 这是我的布局:

preferences.xml 的preferences.xml

<Preference
    android:layout="@layout/preference_gender"
    android:key="seeking"
    android:title="Seeking"/>

preference_gender.xml preference_gender.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout>

<RadioGroup
    android:id="@+id/gender_group"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatTextView
        ...
        android:text="@string/seeking"/>

    <androidx.appcompat.widget.AppCompatRadioButton
        android:id="@+id/male"
        android:text="Male"
        />

    <androidx.appcompat.widget.AppCompatRadioButton
        android:id="@+id/female"
        android:text="Female"
        />

    <androidx.appcompat.widget.AppCompatRadioButton
        android:id="@+id/both"
        android:text="Both"
        />

</RadioGroup>

</androidx.constraintlayout.widget.ConstraintLayout>

Because Preference.OnPreferenceClickListener can't detect specific clicks inside the Preference (only the preference as a whole), I've resorted to adding an onClick() function in the xml which is then passed to my activity: 因为Preference.OnPreferenceClickListener无法检测到内部的特定点击Preference (只偏好作为一个整体),我已经使出添加onClick()在XML,然后传递给我的活动功能:

then to my preferences fragment: 然后到我的偏好片段:

class PreferencesFragment : PreferenceFragmentCompat(), View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preferences, rootKey)
    }


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    gender_group.setOnCheckedChangeListener(this) // null pointer exception
}


}

however I get a NullPointerException on my findPreference("seeking")!! 但是我的findPreference("seeking")!!得到了NullPointerException findPreference("seeking")!! .

Is there any way around this? 有没有办法解决?

preference_gender.xml has no Preference keys at all. preference_gender.xml根本没有Preference键。 A styled RadioGroup & 3 RadioButton might rather be suitable to represent those buttons below a single Preference key; 样式化的RadioGroup &3 RadioButton可能更适合在单个Preference键下面表示这些按钮; nodes alike that AppCompatTextView might be rendered - but won't be treated alike a Preference would be. 类似于AppCompatTextView可能会呈现的节点 - 但不会像Preference那样对待它们。

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

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