0
votes

I want to return my array of images from resource , this is my array for example :

 <integer-array name="drawer_icons">
    <item>@drawable/drawer_home</item>
</integer-array>

I get the array by this code:

val imagesArray =resources.getIntArray(R.array.drawer_icons)

the problem is , after the above code ,imagesArray has a value of 0

how can I return drawable array from resources ?


EDIT: I've made some changes in my codes, I've got another problem , I need to make a data class from these arrays , this is my code:

data class DrawerModel(var title:String, var img: Any)

val titlesArray=resources.getStringArray(R.array.drawer_titles)
    val imagesArray =resources.obtainTypedArray(R.array.drawer_icons)

    val list= ArrayList<DrawerModel>()
    for (i in titlesArray.indices){
        val model=DrawerModel(titlesArray[i],imagesArray[i])
        list.add(model)
    }

I've an error on imagesArray[i] , what should be the type of img in DrawerModel class? I've tried any , Int , String but non of them works

3

3 Answers

1
votes

This is not just an int array. You should use

val imagesArray = resources.obtainTypedArray(R.array.drawer_icons)

val icon = imagesArray.getResourceId(position, -1)

And don't forget to call imagesArray.recycle() after using it.

1
votes

You have to use TypedArray

A TypedArray defined in XML. You can use this to create an array of other resources, such as drawables.

Example :

XML

<integer-array name="drawer_icons">
    <item>@drawable/drawer_home</item>
</integer-array>

Kotlin

val imageArray = resources.obtainTypedArray(R.array.drawer_icons)
val drawable: Drawable = imageArray.getDrawable(0)
1
votes

In Kotlin , you can do as :-

 <integer-array name="drawer_icons">
    <item>@drawable/drawer_home</item>
</integer-array>

// You will get array of Image from resource as TypedArray

 val imageArray = resources.obtainTypedArray(R.array.drawer_icons)

// get resource ID by the index

imageArray.getResourceId(imageArray.getIndex(0),-1)

// OR you can set imageView's resource to the id

imageView.setImageResource(imageArray.getResourceId(imageArray.getIndex(0),-1))

// and in last recycle the array

imageArray.recycle()

For your extending of question , solution would be :-

 data class DrawerModel(var title:String, var img: Int)

 val titlesArray=resources.getStringArray(R.array. drawer_titles)
 val imagesArray =resources.obtainTypedArray(R.array. drawer_icons)

 val list= ArrayList<DrawerModel>()
 for (i in titlesArray.indices){
      val model=DrawerModel(titlesArray[i],imagesArray.getResourceId(imagesArray.getIndex(i),-1))
      list.add(model)
 }