简体   繁体   中英

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM