我正在构建一个首选项活动,其中列表中的大多数首选项都将执行代码,而不是直接修改SharedPreference。我的preferences.xml文件看起来像这样。偏好活动偏好Click Click Listener
<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;
}
});
然后我实际上得到了点击事件的响应。唯一的缺点是我必须删除偏好分组。任何人都知道这是为什么和解决它的方法?
+1您的解决方案暗示了我在我的应用程序中选择的内容。我创建一个String类型的数组,然后为每个数组获取'Preference'并设置'onPreferenceClick'。这是几行代码。谢谢。 – Sufian 2014-08-12 06:15:42
虽然这可能看起来不错,但是使用的方法已被弃用。如果您有更新的答案,请编辑您的帖子。注意getPreferenceScreen()已被弃用。谢谢 – ralphgabb 2015-05-04 00:43:12