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 s开发者_如何学Goelect or click on Asia I can intercept it.
So my (refined) question is how can add a listener to those individual options.
cheers
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;
}
});
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
精彩评论