Proper RadioGroup in PreferenceActivity

前端 未结 3 668
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 07:27

Is it possible to define a RadioGroup in a PreferenceActivity? I could only find the ListView when offering multiple-choices.

Am I missing something?

3条回答
  •  [愿得一人]
    2021-01-20 08:22

    You are welcome to extend any Preference class. I did exactly what you are looking for by extending PreferenceCategory for example. Add child preferences (such as PreferenceScreen and EditTextPreference) like normally with addPreference(), override it and change/ set the widget resource by code with setWidgetLayoutResource(). Naturally, your new widget should contain a RadioButton. Set a custom OnPreferenceClickListener with setOnPreferenceClickListener().

    Next get a reference to the ViewGroup "parent" in onCreateView(). Then you can cast it to ListView in onBindView(), and set a OnHierarchyChangeListener on it. Now you get notified when the child Preference's Views are added to the ListView. Set a new View.OnClickListener on the new View in the hierarchy, but only if the View contains a RadioButton. Now manage the clicks.

    It's actually pretty easy if you only need to add PreferenceScreen as children. I also needed it with a EditTextPreference, which was the tricky part.

    The benefits are simple: you get the default preference framework look and behaviour outside the context of a ListPreference. A ListPreference also looks different. Also, a ListPreference can only contain pre-defined values. So if you need a EditTextPreference to be selected with a radio button, that wouldn't be possible.

提交回复
热议问题