I want to detect when a Preference
contained in a ListView
gets clicked, so that I can launch an intent to manage that selection.
I would have done like this in my layout XML
file:
<Preference android:title="About" android:key="myKey"></Preference>
And the following in my java
code:
Preference myPref = (Preference) findPreference("myKey");
myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//open browser or intent here
}
});
But the method public Preference findPreference (CharSequence key)
is deprecated.
- Is there a non deprecated equivalent?
- If not, what if I use it anyway?
- How can
Fragments
help me do my task in a better way?Chek here: Preferences without deprecated methods.
Here you can check the XML
layout structure that my activity has, and a snapshot of the application:
XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference
android:key="about"
android:title="@string/titleAbout"
android:summary="@string/summaryAbout"
/>
<Preference
android:key="labelTaxonomy"
android:title="@string/titleLabelTaxonomy"
android:summary="@string/summaryLabelTaxonomy"
/>
</PreferenceScreen>
SNAPSHOT:
After clicking on the About (or Access Label Taxonomy) Preference
, I'd like to open an intent
of some kind (could also be a video or anything else...the names are misleading).
maybe docs link are not clear. But using that feature is very simple. for example, you can use that as a twitter page like this
it doesnt need any java code. Thanks to CommonsWare!
2018 UPDATE Today, the
onPreferenceTreeClick
method has to be overriden in the Preference fragment for this purpose. For example:If you use fragments, you can use the method "findPreference()" on the basis of a preferences fragment.
If you are using
PreferenceFragment
on API Level 11+ devices, you would callfindPreference()
on it. Otherwise, callfindPreference()
on yourPreferenceActivity
, as you have no choice.It will work.
API Level 11+ introduced
PreferenceFragment
as another way of constructing the contents of aPreferenceActivity
. You are welcome to use them, but if you are still supporting older devices, you cannot usePreferenceFragment
for those devices.That being said:
You do not need Java code for this. Use:
(as seen in the JavaDocs for
PreferenceActivity
)This will create an entry in the preference UI that, when clicked, will start an activity with the specified
Intent
.