fobus
fobus

Reputation: 2058

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?

Upvotes: 3

Views: 2990

Answers (1)

Ryan S
Ryan S

Reputation: 4567

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()!

Upvotes: 1

Related Questions