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
:
Here is my layout:
preferences.xml
<Preference
android:layout="@layout/preference_gender"
android:key="seeking"
android:title="Seeking"/>
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:
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")!!
.
Is there any way around this?
preference_gender.xml
has no Preference
keys at all. A styled RadioGroup
& 3 RadioButton
might rather be suitable to represent those buttons below a single Preference
key; nodes alike that AppCompatTextView
might be rendered - but won't be treated alike a Preference
would be.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.