How to set multiple default values in a MultiSelectListPreference?

◇◆丶佛笑我妖孽 提交于 2019-12-23 06:55:02

问题


I have preference.xml like this

<MultiSelectListPreference
        android:key="store_select"
        android:title="@string/setting_store_title"
        android:summary="@string/setting_store_summary"
        android:dialogTitle="@string/setting_store_dialog_title"
        android:entries="@array/store_names"
        android:entryValues="@array/stores"
        android:defaultValue="@array/stores"
        />

with my two arrays:

    <string-array name="stores">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
</string-array>

<string-array name="store_names">
    <item>foodbasics</item>
    <item>nofrills</item>
    <item>metro</item>
    <item>loblaws</item>
    <item>sobeys</item>
</string-array>

I want the default behaviour to be all of the options selected, but currently nothing is selected by default. Am I doing something wrong?


回答1:


To make all MultiSelectListPreference items selected (on) by default, then include the attribute defaultsValue for the Preference, e.g.

android:defaultValue="@array/stores"

If it's not working, then make sure that you clear the application data as this will only take effect the first time the application is run.




回答2:


I think you forgot calling PreferenceManager.setDefaultValues(this, R.xml.preference, false); in the onCreate() method of your mainActivity.

This method will read your preference.xml file and set the default values defined there. Setting the readAgain argument to false means this will only set the default values if this method has never been called in the past so you don't need to worry about overriding the user's settings each time your Activity is created.




回答3:


I know I am late but may be my answer helps someone else in future...

set

android:defaultValue="@array/empty_array"

where empty_array is an empty array.




回答4:


If you are adding MultiSelectListPreference programmatically then you can simply call multiSelectListPreference.setDefaultValue():

e.g.

val preference = MultiSelectListPreference(context)
preference.setDefaultValue(setOf("US, "CN"))


来源:https://stackoverflow.com/questions/15628558/how-to-set-multiple-default-values-in-a-multiselectlistpreference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!