How to set the value and item checked of a listpreference in an onchangelistener

207 Views Asked by At

I'm having problems updating the value of a ListPreference. ListPreference.setDefaultValue() and ListPreference.setIndexValue() don't seem to be recognized methods.

I want to "reset" all other ListPreferences when one of their buddy ListPreferences are clicked, so that only one of them has a valid value at any given time.

Also, the android:defaultValue="1" in the XML file doesn't seem to work either, at least not in view. Does this only change the actual value? Does it not check the first value as well?

The ListPreferences are behaving like they should other than that, so I'm sure the xml files are good. I'm using androidx, I have implemented androidx.preference:preference:1.0.0

Class SettingsActivity : AppCompatActivity() {

  Class SettingsFragment : PreferenceFragmentCompat() {
    override fun onPreferenceCreated() {
      setPreferencesFromResource(R.xml.prefs)
    }

    fun onCreate(savedInstances) {
      val listPreference1 = findPreference(listpreference1)
      val listPreference2 = findPreference(listpreference2)

      listPreference1.setOnChangeListener { preference: Preference, newValue: Any ->

      //listPreference2.         <---- This is where the expected methods aren't showing. Not setDefaultValue, setValue, setIndexValue.

      true ^setOnchangeListener
    }
  }
}

I don't actually get to the results as I can't use the method that I need.

If you need any other information I'll try to provide more.

Thank you

1

There are 1 best solutions below

0
Thibault Seisel On

findPreference(String) is the correct method for retrieving a reference to your ListPreferences. The problem is that it returns a variable of type Preference, which is the base class for all UI settings components. If you need to access features that are only available to ListPreference, and you are sure that that preference is a ListPreference (i.e., it is defined as a ListPreference in your XML file), you can safely cast it :

val listPreference1 = findPreference("my_list_preference_1") as ListPreference

This way, you should be able to use methods that are specific to ListPreference :

listPreference1.setValue("Whatever you'd like")

Note that this is not specific to Kotlin, this is how Object-Oriented Programming works : you can only call methods on a object that are defined by its interface. If you want to call methods of a subclass, you need to make the assertion that this object is an instance of that subclass (that's what we call a "cast", done with the as syntax in Kotlin).

Also, I suggest that you call findPreference in onCreatePreferences, after setPreferencesFromResources(R.xml.prefs), otherwise you'll likeky get a NullPointerException.