Listener button does not work in preference fragment

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

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

I declare preference in OnCreate as follows:

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

The callback is called when the first view is opened (the breakpoint in the callback hits), but does not print the logs, and the callback is never called again, even when I turn the switch on and off. How can I make this feedback?

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

+6
source share
2 answers

I see that you are trying to use PreferenceFragment like any other normal fragment. However, you must consider the correct mechanism, for example, you cannot use all widgets to represent preferences for the user, you must use Preference (see Subclass).

Another example: you should use addPreferencesFromResource(int) to inflate settings from an XML resource.

Check both links above and example .

Hope this helps you.

+8
source

If you use Jorge Gil's anwser, you won’t be able to easily get a link to the view that you are announcing on the PreferenceScreen. However, you can easily get one of the preference objects, which in this case is 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 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; } }); 
+2
source

Source: https://habr.com/ru/post/947144/


All Articles