Java 将 Strings.xml 中的 String-Array 更改为 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19127071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:19:43  来源:igfitidea点击:

Change String-Array in Strings.xml to ArrayList

javaandroidarraysstringarraylist

提问by hichris123

I'm developing an Android app. I need to convert a string array into an ArrayList. I've read up on this, and all have cases where you add the values to the array in the java file. I have declared the string-array in the strings.xml file. My string-array is here:

我正在开发一个 Android 应用程序。我需要将字符串数组转换为 ArrayList。我已经阅读了这一点,并且都有将值添加到 java 文件中的数组的情况。我已经在 strings.xml 文件中声明了字符串数组。我的字符串数组在这里:

<string-array name="Lines">
    <item>Red Line</item>
    <item>Blue Line</item>
    <item>Orange Line</item>
    <item>Green Line</item>
    <item>Brown Line</item>
    <item>Purple Line</item>
    <item>Pink Line</item>
    <item>Yellow Line</item>
</string-array>

I need to convert Lines into ArrayList. If I use this

我需要将 Lines 转换为 ArrayList。如果我用这个

List<String> Lines = new ArrayList<String>();

to declare the ArrayList, how can find the array list by ID, and store that as Lines?

要声明 ArrayList,如何通过 ID 找到数组列表,并将其存储为 Lines?

采纳答案by Melih Mucuk

Try this;

尝试这个;

List<String> Lines = Arrays.asList(getResources().getStringArray(R.array.Lines));

and this for kotlin:

这对于科特林:

val Lines = resources.getStringArray(R.array.Lines).toList()

回答by Waqar UlHaq

In strings.xml, add string array

在strings.xml中,添加字符串数组

<string-array name="dashboard_tags">
    <item>Home</item>
    <item>Settings</item>
</string-array>

In your .java class access the string array like

在您的 .java 类中访问字符串数组,如

List<String> tags = Arrays.asList(getResources().getStringArray(R.array.dashboard_tags));

回答by OhhhThatVarun

If anybody wondering how to do the same in kotlin

如果有人想知道如何在kotlin 中做同样的事情

val universities = arrayListOf<String>(*resources.getStringArray(R.array.universities))

universitieswill be ArrayList<String>

universities将会 ArrayList<String>

回答by Silambarasan

This is the best practice without any warning

这是没有任何警告的最佳实践

Add string array to arraylist:

将字符串数组添加到数组列表:

Collections.addAll(Lines, getResources().getStringArray(R.array.Lines));

To add one ArrayList to another:

将一个 ArrayList 添加到另一个:

newList.addAll(oldList);