Proper RadioGroup in PreferenceActivity

前端 未结 3 441
广开言路
广开言路 2021-01-20 07:59

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:02

    Is it possible to define a RadioGroup in a PreferenceActivity?

    You are welcome to create your own DialogPreference subclass that happens to host a RadioGroup, but it is unclear what benefit that would give you over a ListPreference.

    I could only find the ListView when offering multiple-choices.

    A ListPreference offers single choices, not multiple choices. There is a new MultiSelectListPreference for multiple choices, but that only showed up in API Level 11.

    0 讨论(0)
  • 2021-01-20 08:04

    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.

    0 讨论(0)
  • 2021-01-20 08:28

    Look at API Demos App - Preferences - Preferences from XML or others examples.

    You can basically copy that code. There is an entry that display a list with a radio group.

    I don't have the code right now, but you can take a look here, it's similar:

    http://www.kaloer.com/android-preferences

    <ListPreference
                        android:title="List Preference"
                        android:summary="This preference allows to select an item in a array"
                        android:key="listPref"
                        android:defaultValue="digiGreen"
                        android:entries="@array/listArray"
                        android:entryValues="@array/listValues" />
    
    0 讨论(0)
提交回复
热议问题