LoginSignup
0
0

More than 5 years have passed since last update.

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

Posted at

単純に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);

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0