Adding listeners to individual ListPreference items

寵の児 提交于 2019-12-06 13:48:24
K1988
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;
    }
});

OnSharedPreferenceChangeListener is called when persistent = true after the sharedPref value was changed, but for each item you can actually assign its own OnPreferenceChangeListener and there you see which item was clicked

ListPreference pLocAuto = (ListPreference) findPreference(PREF_LOC_AUTO);
pUpdateAuto.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                System.out.print(newValue.toString());
                return false;
            }
        });
Julian Vogels

I think there's another post on stackoverflow that is similar to this one: Custom Row in a ListPreference.

In this one, subclassing is the solution. But may be in your case you can use a simple ListAdapter.

If you have set up the adapter, you can use the method onItemClick and inside the method you can use a switch statement (case is the id or the index in an array or anything like this) to call different methods.

I hope I understood your question... :)

Ah! You also need to have a look on the onFocusChange Listener. You can add this Listener to every Preference Item (which has to be a View; you add the listener in the adapter), then in the listener method have the announced switch statement.

Greetings and i hope i could provide you a hint,

Julian

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!