如何正确使用androidx的下拉菜单偏好设置(DropdownPreference)?

4

我正在使用下拉菜单偏好设置,但是每次尝试展开时应用程序都会崩溃。应该如何填写entryValues和entries字段?官方文档没有关于XML用法的解释。在api 25和21上测试过。

<androidx.preference.PreferenceCategory app:title="@string/Time">

    <androidx.preference.DropDownPreference
        android:key="dropdown"
        android:title="@string/waitTime"
        android:entryValues="@array/planets_array"
        android:entries="@array/times"
        app:useSimpleSummaryProvider="true"
        />


</androidx.preference.PreferenceCategory>
</androidx.preference.PreferenceScreen>

string.xml:

 <resources>
    <string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
</string-array>

<integer-array name="times">
    <item>5</item>
    <item>10</item>
    <item>15</item>
    <item>20</item>

</integer-array>
</resources>

日志:

Process: com.example.detector, PID: 11439
android.view.InflateException: Binary XML file line #22: Error inflating class androidx.preference.DropDownPreference
    ...
androidx.preference.PreferenceFragmentCompat.setPreferencesFromResource(PreferenceFragmentCompat.java:377)
    at com.example.breathdetector.ui.customization.CustomizationFragment.onCreatePreferences(CustomizationFragment.java:24)
 androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
   ...
 Caused by: java.lang.reflect.InvocationTargetException
   ...androidx.preference.PreferenceFragmentCompat.setPreferencesFromResource(PreferenceFragmentCompat.java:377) 
    at com.example.breathdetector.ui.customization.CustomizationFragment.onCreatePreferences(CustomizationFragment.java:24) 
    at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:160) 
    at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586) 
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838) 
    at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100) 
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874

非常感谢您的帮助。

1个回答

4

看一下这个样本:

数组 XML

首选项 XML

从堆栈跟踪很难确定,但可能是因为您正在使用整数数组——我认为 DropDownPreference 只能使用字符串数组作为条目和条目值。

希望这可以帮助!


链接是404。请更新。 - Qadir Hussain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接