Help us understand the problem. What is going on with this article?

Androidでcolorを配列で指定してリソースIDを取得する方法

More than 3 years have passed since last update.

単純にgetResources().getIntArray(R.array.color_list)だとリソースIDの配列として取得ができなかった。。。

以下のカラー配列をcolors.xmlに定義

colors.xml
    <array name="color_list">
        <item>@android:color/white</item>
        <item>@android:color/gray</item>
        <item>@android:color/black</item>
        <item>@android:color/red</item>
    </array>

javaコードからカラー配列を取得して、リソースIDを取得する

ColorListActivity.java
private int[] getColors() 
{
        int[] colorList;
        // colors.xmlからカラー配列を取得する
        TypedArray colors = getResources().obtainTypedArray(R.array.color_list);
        if (colors.length() <= 0) {
            return null;
        }

        // リソースID用の配列を準備
        colorList = new int[colors.length()];
        for (int ii=0; ii<colors.length(); ii++) {
            // TypedArrayから指定indexのTypedValueを取得する
            TypedValue colorValue = new TypedValue();
            if (colors.getValue(ii, colorValue)){
                // TypedValueからリソースIDを取得する
                colorList[ii] = colorValue.resourceId;
            }
        }
        return colorList;
}

取得したリソースIDでカラー設定してあげれば色が反映される

各要素.setColor(resourceId);

もっと簡単なやり方があれば、教えて下さーーい。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away