从字符串 xml 数组填充自定义微调器

populate custom spinner from strings xml array

我有一个 custom spinner,它正在替换我的默认值 spinner,它由我的 strings xml.

中的硬编码值填充

我已经使用了我的 custom spinner and populated it dynamically in java,但我不需要为这个做这个。

我是否必须填充一个列表然后将其添加到 java 中的微调器?如果是这样,我如何从 strings.xml 数组元素填充列表?

    List<String> spinnerList = new ArrayList<String>();
    //spinnerList.addAll(R.array.array_spinner);error here, doesnt like this?????????????
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_custom, spinnerList);
    spinnerSports.setAdapter(adapter);

<resources>
    <string-array name="array_custspinner">
        <item>item1</item>
        <item>item2</item>
    </string-array>
</resources>

//spinnerList.addAll(R.array.array_spinner);error here, doesnt like this?????????????

是的,它是正确的。 addAll 期望 Collection 与您的 ListString 类型相同。但是你提供了一个int,你想使用的数组的id。使用

List<String> spinnerList = new ArrayList<String>
      (Arrays.asList(getResources().getStringArray(R.array.array_custspinner)));

这样你就可以得到一个可修改的 List<String> 其中包含你在 array_custspinner

中定义的所有字符串