Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding listeners to individual ListPreference items

I'm trying to add individual listeners to items in a ListPreference but I just can't find the right code to do it.

For example, assume I have an app where needs the region to be set. So I have a ListPreference with three options; Americas, Asia, Europe.

When I use the trackpad to scroll through the items I would like them to speak the text of the preference when they get focus.

I'm sure somewhere in the API I can add a listener to the individual items but I just can not find it. There is a setOnPreferenceClickListener(..) method in ListPreference (inherited from DialogPreference) but that is for when you select the actual parent preference item.

Do I need to write a special subclass?

EDIT

After looking into this more I think I need to further clarify my question. When using preferences you can override the onPreferenceTreeClick (PreferenceScreen prefScreen, Preference pref) method in the PreferenceActivity. This allows you to intercept any clicks on preferences. However I want to add a listener to the actual dialog that pops up. The "Americas, Asia, Europe" options from the above example. So if I select or click on Asia I can intercept it.

So my (refined) question is how can add a listener to those individual options.

cheers

like image 816
Tim Avatar asked Jul 10 '26 13:07

Tim


1 Answers

final ListPreference list = (ListPreference) preference;
list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    public boolean onPreferenceChange(Preference preference, Object newValue) {

        int index = list.findIndexOfValue(newValue.toString());

        if (index != -1) {
            Toast.makeText(getBaseContext(), list.getEntries()[index], Toast.LENGTH_LONG).show();
        }
        return true;
    }
});
like image 182
fmgh Avatar answered Jul 12 '26 05:07

fmgh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!