goRGon goRGon - 2 years ago 122
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">

android:summary="@string/prefs1_summary" />

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

new OnPreferenceClickListener() {

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download