Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button listener not working in Preference fragment

Tags:

android

I've created a subclass of PreferenceFragment that implements CompoundButton.OnCheckedChangeListener. I have one preference that contains a Switch (a subclass of CompoundButton). Here's the callback I've created for when the value of the switch changes:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    mAppController.doSomething(isChecked);
    Log.v("rose_tag", "hi");
}

I declare the preference in OnCreate as follows:

Switch mySwitch = (Switch) myView.findViewById(R.id.switch);
mySwitch.setEnabled(true);
mySwitch.setOnCheckedChangeListener(this);

The callback gets called when the view first opens (a breakpoint in the callback is hit), but no log prints, and the callback never gets called again, even when I switch the switch on and off. How can I make this callback work?

I also tried creating an inline anonymous listener. I also tried using a simple Button with an onClick listener, and that didn't work either.

like image 865
Rose Perrone Avatar asked Jun 12 '13 18:06

Rose Perrone


2 Answers

I can see you are trying to use PreferenceFragment as any other normal fragment. However, you must to take in count the correct mechanism, one example is you cannot use all the widgets for making a preferences view for the user, you must use the Preference objects (see Preference subclasses).

Another example is that you must use addPreferencesFromResource(int) to inflate preferences from an XML resource.

Check both links above and this example.

I hope It helps you.

like image 60
Jorge Gil Avatar answered Oct 09 '22 09:10

Jorge Gil


If you use the anwser from Jorge Gil, you will not be able to easily get a reference to the view you are declaring in the PreferenceScreen. However you can easily get one of the preference Object which in that case is a SwitchPreference. So in your res/xml/preferences.xml add your switch preference:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="screen">

    <SwitchPreference
            android:key="switch_preference"
            android:title="title"
            android:summary="summary" />

</PreferenceScreen>

Then in your PreferenceFragment/PreferenceActivity's onCreate function add this:

    addPreferencesFromResource(R.xml.preferences);      
    SwitchPreference switchPref = (SwitchPreference) findPreference("switch_preference");

    switchPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Log.e(getClass().getSimpleName(),"onPreferenceChange:" + newValue);
            return true;
        }
    });
like image 32
Gomino Avatar answered Oct 09 '22 09:10

Gomino