我正在构建一个首选项活动,其中列表中的大多数首选项将执行代码而不是直接修改 SharedPreference。我的preferences.xml 文件看起来像这样。
<PreferenceCategory
android:title="Connection" >
<Preference
android:id="@+id/settings_connectToNewComputer"
android:key="connectToNewComputer"
android:summary="Currently connected to:"
android:title="Connect to new computer" />
<Preference
android:id="@+id/removeDevice"
android:key="removeDevice"
android:summary="Remove this device from the computer's whitelist"
android:title="Remove this device from computer" />
</PreferenceCategory>
<PreferenceCategory
android:title="About" >
<Preference
android:id="@+id/settings_About"
android:key="about"
android:summary="About me and my thanks to those who made this app great"
android:title="About Hue Pro" />
<Preference
android:id="@+id/contact"
android:key="contact"
android:summary="Contact me with comments, bugs, and suggestions for updates"
android:title="Contact me" />
</PreferenceCategory>
我的目标是在单击其中一个首选项时执行一段代码。类似于 Google Play 设置偏好菜单中的“清除搜索历史”。( http://i.imgur.com/qnHbJX9.png )
有谁知道如何使这成为可能?
我必须补充一点,我尝试过使用 findPreference("KeyNameHere") 但它总是返回 null。
谢谢!
编辑:
我在这段代码中添加并实现了 OnPreferenceClickListener:
@Override
public boolean onPreferenceClick(Preference preference) {
return false;
}
但是这个方法永远不会被调用。还有另一种方法可以做到这一点吗?
编辑2:
我发现如果我取出 PreferenceCategory 标签,那么我就剩下这个了:
<Preference
android:id="@+id/settings_connectToNewComputer"
android:key="connectToNewComputer"
android:summary="Currently connected to:"
android:title="Connect to new computer" />
<Preference
android:id="@+id/removeDevice"
android:key="removeDevice"
android:summary="Remove this device from the computer's whitelist"
android:title="Remove this device from computer" />
<Preference
android:id="@+id/settings_About"
android:key="about"
android:summary="About me and my thanks to those who made this app great"
android:title="About Hue Pro" />
<Preference
android:id="@+id/contact"
android:key="contact"
android:summary="Contact me with comments, bugs, and suggestions for updates"
android:title="Contact me" />
并称之为:
getPreferenceScreen().setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
return false;
}
});
然后我实际上得到了点击事件的响应。唯一的缺点是我必须删除首选项分组。任何人都知道这是为什么以及任何解决方法?