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 h
Is there a non deprecated equivalent?
If you are using PreferenceFragment
on API Level 11+ devices, you would call findPreference()
on it. Otherwise, call findPreference()
on your PreferenceActivity
, as you have no choice.
If not, what if I use it anyway?
It will work.
How can Fragments help me do my task in a better way?
API Level 11+ introduced PreferenceFragment
as another way of constructing the contents of a PreferenceActivity
. You are welcome to use them, but if you are still supporting older devices, you cannot use PreferenceFragment
for those devices.
That being said:
I want to detect when a Preference contained in a ListView gets clicked, so that I can launch an intent to manage that selection.
You do not need Java code for this. Use:
<PreferenceScreen
android:title="@string/title_intent_preference"
android:summary="@string/summary_intent_preference">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.android.com" />
</PreferenceScreen>
(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
.
2018 UPDATE
Today, the onPreferenceTreeClick
method has to be overriden in the Preference fragment for this purpose. For example:
public class MySettingsFragment extends PreferenceFragment {
@Override
public boolean onPreferenceTreeClick (PreferenceScreen preferenceScreen,
Preference preference)
{
String key = preference.getKey();
if(key.equals("someKey")){
// do your work
return true;
}
return false;
}
}
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
<PreferenceCategory android:title="Share" >
<PreferenceScreen
android:title="Twitter"
android:summary="Follow me at Twitter">
<intent android:action="android.intent.action.VIEW"
android:data="https://twitter.com/" />
</PreferenceScreen>
</PreferenceCategory>
it doesnt need any java code. Thanks to CommonsWare!
If you use fragments, you can use the method "findPreference()" on the basis of a preferences fragment.
public class CustomActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom);
CustomFragment customFragment = (CustomFragment) getFragmentManager().findFragmentById(R.id.custom_fragment);
EditTextPreference textPreference = (EditTextPreference) customFragment.findPreference("preference_key");
textPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//open browser or intent here
}
});
}
}