Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setOnPreferenceClickListener function doesn't work for Preference on Android

I'm using the code below to print text to logcat, but the setOnPreferenceClickListener function doesn't catch the event.

I'm using Android API Level 8 to test the code.

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="settings_use_cache"
        android:summary="Use cache"
        android:title="Use Cache" />

    <Preference
        android:defaultValue="true"
        android:key="settings_delete_cache"
        android:summary="Delete all cache data"
        android:title="Clear Cache" />

</PreferenceScreen>

Here is the code

public static class CachePreferenceFragment extends
        PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {

        Log.w("DBG", "Oncreate started");

        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_cache);

        Preference settings_delete_cache=findPreference("settings_delete_cache");
        settings_delete_cache.setOnPreferenceClickListener(new OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                Log.w("Prefence", "Deleting Cache");
                return false;
            }
        });         
    }
}

What can I do to ensure the listener catches the event?

like image 539
fobus Avatar asked Dec 21 '25 06:12

fobus


1 Answers

EDIT: After talking with this dev outside of the thread, it was identified that the problem was that he was putting his listener inside of the fragment. So this code actually works, but it will only run if you are using a two-panel layout. In fact this is stated right above the method:

    /**
     * This fragment shows notification preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */

    public static class CachePreferenceFragment extends
            PreferenceActivity {

The solution is to also set the onPreferenceClick listener in setupSimplePreferencesScreen()!

like image 137
Ryan S Avatar answered Dec 22 '25 21:12

Ryan S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!