在我的应用程序中,我想在我的首选项活动中的各个首选项列表项上设置一个单击侦听器,问题是我只能找到如何在主要listprefernce本身上设置一个单击侦听器,有没有办法我可以设置单个列表项的键,所以当我设置OnPreferenceClickListener时,我可以执行一些列表项特定的代码?
make sure your preference class implements
OnPreferenceClickListener and then override the onPreferenceClick
then just check what preference key was pressed
@Override
public boolean onPreferenceClick(Preference preference) {
if (preference.getKey().equals("schedulestart")) {
showDialog(0);
} else if (preference.getKey().equals("schedulestop")) {
showDialog(1);
} else if (preference.getKey().equals("priority")) {
getPreferenceManager().getSharedPreferences().edit().putInt("unreadcount", 0).commit();
}
return true;
}
This question is relatively ancient, but I was looking to do a similar thing -- specifically get a hook in whenever any ListPreference item is clicked. Things like onSharedPreferenceChanged did not work for me because I need to do something even when the currently selected ListPreference is clicked. I'm not sure I understand the other answer here as solving the problem. My googling hasn't uncovered any other solutions.
I went along with extending ListPreference and overriding onDialogClosed(). The ListPreference source code for onDialogClosed is
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
}
}
}
I created a working interface to send the value of the selected list item in my new ListPreference and then overrode onDialogClosed:
public class MyListPreference extends ListPreference {
private ListItemClickListener mListItemClickListener;
...
public void setOnListItemClickListener(ListItemClickListener listener) {
mListItemClickListener = listener;
}
public interface ListItemClickListener {
public void onListItemClick(String value);
}
...
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && getEntryValues() != null && mListItemClickListener != null) {
String value = getValue();
mListItemClickListener.onListItemClick(value);
}
}
Then, in your settings activity (or wherever you are using the new ListPreference), just hook it in:
@Override
protected void onResume() {
super.onResume();
MyListPreference listPref = (MyListPreference)
findPreference(getString(R.string.key_name));
listPref.setOnListItemClickListener(this);
}
...
public void onListItemClick(String value) {
// Do something
}
This works for my purposes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.