Leo
Leo

Reputation: 21

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)

Upvotes: 0

Views: 633

Answers (2)

Iman Marashi
Iman Marashi

Reputation: 5753

Here's a simple solution:

resources.obtainTypedArray(R.array.reception_tabs).apply {
            for (i in 0 until this.length()) {
                binding.tabLayout.addTab(binding.tabLayout.newTab().apply {
                    title = getText(i).apply {
                        Log.d(TAG, "initViewPager: $this")
                    }
                })
            }
        }

Upvotes: 0

Leo
Leo

Reputation: 21

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

Upvotes: 1

Related Questions