How I can get IntArray of view ids from resource XML (Android)

727 Views Asked by At

I have array in file res/values/ids.xml

<array name="first_set">
    <item>@id/layout1</item>
    <item>@id/layout2</item>
    <item>@id/layout3</item>
    ...
</array>

I tried to get these ids, but it didn't work(((

    val typedArray = resources.obtainTypedArray(viewSetId)
    val idSet = IntArray(typedArray.length())
    for (i in 0 until typedArray.length()) {
        idSet[i] = typedArray.getInt(i, 0)
    }
    typedArray.recycle()

All idSet's elements equals 0.

I also tried store integer array in res/values/integers.xml

<integer-array name="first_set">
    <item>@id/layout1</item>
    <item>@id/layout2</item>
    <item>@id/layout3</item>
    ...
</integer-array>

And then get these ids

val idSet = resources.getIntArray(R.array.first_set)

But result is the same((

2

There are 2 best solutions below

1
On

Use @+id to ensure they are created by the time the array is generated:

<integer-array name="first_set">
    <item>@+id/layout1</item>
    <item>@+id/layout2</item>
    <item>@+id/layout3</item>
    ...
</integer-array>
1
On

IntArray Xml should be like this Format

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <integer-array name="first_set">
       <item>@id/layout1</item>
       <item>@id/layout2</item>
       <item>@id/layout3</item>
 </integer-array>
</resources>

in the path xml resource in res/values/integers.xml

Access the xml data in the activity like this way

 val arrayValues = resources.getIntArray(R.array.first_set)