简体   繁体   中英

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

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 ListPreference s when one of their buddy ListPreference s 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 ListPreference s 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

findPreference(String) is the correct method for retrieving a reference to your ListPreference s. 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 (ie, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM