androidkotlinresourcesdrawabletyped-arrays

How to get the index of an item in a typed array?


I want to store drawables in a resource array like this:

    <integer-array name="sensor_icon_values">
        <item>@drawable/sensor_brightness</item>
        <item>@drawable/sensor_temperature</item>
        <item>@drawable/sensor_humidity</item>
        <item>@drawable/sensor_carbon_dioxide</item>
        <item>@drawable/sensor_voltage</item>
    </integer-array>

How can I get the index of a certain item in kotlin? Lets say I want to get the index of the element with the resourceId of 2131230874.

I know that I probably have to use a typed array like this:

val sensorIcons = resources.obtainTypedArray(R.array.sensor_icon_values)


Solution

  • Here's a solution that worked my use case:

            val typedArray = resources.obtainTypedArray(R.array.sensor_icon_values)
            for (i in 0..typedArray.length()){
                if (selectedIconResourceId == typedArray.getResourceId(i,0)){
                    iconPreference?.setValueIndex(i)
                    break
                }
            }
            typedArray.recycle()