我正在構建一個首選項活動,其中列表中的大多數首選項都將執行代碼,而不是直接修改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