简体   繁体   中英

Cant set string default value for ListPreference android preferencescreen

I have seen other similar unanswered question on SO. I could not find a solution. From other answers I'm using 'defaultValue' on xml but that does not set the default value of ListPrefrenece. So the listPreference says 'not set' instead of defaultvalue when it is installed. Here is the ListPreference:

<ListPreference
        android:widgetLayout="@layout/arr_dn"
        app:defaultValue="reply"
        app:entries="@array/Sweets_entries"
        app:entryValues="@array/Sweets_values"
        app:key="Sweets"
        app:title="Sweets"
        android:defaultValue="@string/defaultSweets"
        app:useSimpleSummaryProvider="true" />

String values:

<string name="defaultSweets">NormalSweets</string>


<string-array name="Sweets_values">
        <item>Very Sweet</item>
        <item>NormalSweets</item>
        <item>Less Sweet</item>
    </string-array>

I used PreferenceFragmentCompat activity and it does not recognize 'onSetInitialValue' method. I dont know where to implement that method. I want set a value only so that it doesnot say 'not set' when installed.

How can I set a string value as default value for this ListPreference?

With below code I was able to set default value to a ListPreference by extending PreferenceFragmentCompat to a fragment.

<ListPreference
    android:defaultValue="@string/pref_units_metric"
    android:entries="@array/pref_units_options"
    android:entryValues="@array/pref_units_values"
    android:key="@string/pref_units_key"
    android:title="@string/pref_units_label" />

String values:

<string name="pref_units_metric">metric</string>

<string-array name="pref_units_options">
    <item>@string/pref_units_label_metric</item>
    <item>@string/pref_units_label_imperial</item>
</string-array>

<string-array name="pref_units_values">
    <item>@string/pref_units_metric</item>
    <item>@string/pref_units_imperial</item>
</string-array>

I noticed that you have set two defaultValue attributes in your xml file. Just try and remove app: package and keep only android: ones. Hope it helps you!!!

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