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

时间:2013-10-01 22:28:20

标签: java android arrays string arraylist

我正在开发一款Android应用。我需要将字符串数组转换为ArrayList。我已经读过这篇文章了,所有的情况都是你在java文件中将值添加到数组中的情况。我在strings.xml文件中声明了string-array。我的字符串数组在这里:

<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>

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

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

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

4 个答案:

答案 0 :(得分:117)

试试这个;

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

答案 1 :(得分:2)

如果有人想知道如何在 kotlin

中执行相同的操作
$msg = array
(
    "webpush" =>  array
    (
        "notification" =>  array
        (
            "title" =>  "Fish Photos ?",
            "body" =>  "Thanks for signing up for Fish Photos! You now will receive fun daily photos of fish!",
            "icon" =>  "firebase-logo.png",
            "image" =>  "guppies.jpg",
            "data" =>  array
            (
                "notificationType" =>  "fishPhoto",
                "photoId" =>  "123456",
            ),
            "click_action" =>  "https://example.com/fish_photos",
            "actions" =>  array(
                0 => array(
                    'title' => 'Like',
                    'action' => 'like',
                    'icon' => 'icons/heart.png',
                ),
                1 => array(
                    'title' => 'Unsubscribe',
                    'action' => 'unsubscribe',
                    'icon' => 'icons/cross.png',
                ),
            ),
        ),

    ),
);

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

答案 2 :(得分:1)

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

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

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

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

答案 3 :(得分:0)

这是没有任何警告的最佳做法

将字符串数组添加到arraylist:

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

要将一个ArrayList添加到另一个:

newList.addAll(oldList);