goRGon goRGon - 26 days ago 12
Android Question

Why does Android ignore OnPreferenceClickListener() that returns true?

I defined my preferences in xml file like the following:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceScreen
android:title="@string/pref_screen"
android:key="pref_screen_key">

<CheckBoxPreference
android:defaultValue="true"
android:key="prefs1_key"
android:title="@string/prefs1_str"
android:summary="@string/prefs1_summary" />
....


Inside PreferenceActivity I override onPreferenceClick() for "pref_screen_key":

...
findPreference("pref_screen_key").setOnPreferenceClickListener(
new OnPreferenceClickListener() {

@Override
public boolean onPreferenceClick(Preference preference) {
if (flag) {
// do some stuff
return true; // According to Android doc it means, that click was handled
} else
return false;
}


So I wish that Android will not open view with CheckBoxPreference if my flag is true, but just executes my stuff (I return true inside onPreferenceClick() to indicate that the click was handled and it is not needed to execute the default onPreferenceClick() behavior).
Unfortunately, Android always handles onPreferenceClick() with default behavior and makes my stuff at the same time.

Is it a bug in Android?
Is there a way to prevent Android from showing CheckBoxPreference after user clicks on PreferenceScreen?

Answer

You're probably running into problems with the fact that the flag must be declared final to be accessed inside the OnPreferenceClickListener. Try encapsulating it in a class and declaring the class final.

To more directly answer your question, remember that when you return true from onPreferenceClick(), you're telling the system "don't worry, I handled it." So, when you simply return true without actually doing anything, the system isn't ignoring you, per se, you just told it to do nothing when the Preference is clicked.

Your code looks similar to lines 108-115 of this example. Look through that and it may help.

Comments