LoginSignup
12
14

More than 5 years have passed since last update.

array resourceから各要素のresource idを取得する

Last updated at Posted at 2015-01-13

たまにしか使わないので忘れるため、メモ。

strings.xml
<string name="hoge">ほげ</string>
<string name="piyo">ぴよ</string>
<string name="fuga">ふが</string>
arrays.xml
<string-array name="array">
    <item>@string/hoge</item>
    <item>@string/piyo</item>
    <item>@string/fuga</item>
</string-array>

上記のようなresourceがある場合に { "ほげ, "ぴよ", "ふが" } ではなく、
{ R.string.hoge, R.string.piyo, R.string.fuga } を取得する方法。

配列リソースからリソースID配列の取得
public static int[] getResourceIds(Resources resources, int arrayId) {
    final TypedArray array = resources.obtainTypedArray(arrayId);
    try {
        final int[] resourceIds = new int[array.length()];
        for (int i = 0; i < resourceIds.length; ++i) {
            resourceIds[i] = array.getResourceId(i, 0);
        }
        return resourceIds;
    } finally {
        array.recycle();
    }
}

なお、array内のitemがresourceではなく、下記のように直接値を指定している場合は、TypedeArray#getResourceIdの第2引数の値になる(上記の0)。

arrays.xml
<string-array name="array">
    <item>ほげ</item>
    <item>ぴよ</item>
    <item>ふが</item>
</string-array>
12
14
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
12
14