Issue
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
Solution
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)
}
Answered By - Alok Mishra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.