Drawables name in a list of all drawables kotlin

Viewed 57

This is my class, here I make a call with all the Drawables, But the moment I do "drawableList.toString()" return the name as "android.graphics.drawable.bitmap@65vd6f5" and I would like the return to be "R.drawable.icon_outline_airplane". can anybody help me?

class IconComponenteRecyclerAdapter : RecyclerView.Adapter<IconComponenteRecyclerAdapter.ViewHolder>() {

    var drawableList = getAllDrawables().filter { it.toString().startsWith("android.graphics.drawable.") }

    private fun getAllDrawables(): List<Drawable?> {
        return R.drawable::class.java.fields.map {
            ResourcesCompat.getDrawable(resources, it.getInt(null), null)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IconComponenteRecyclerAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.icon_component_card, parent, false)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return drawableList.size
    }

    override fun onBindViewHolder(holder: IconComponenteRecyclerAdapter.ViewHolder, position: Int) {
        holder.itemTitle.text = drawableList[position].toString().removePrefix("android.graphics.drawable.")
        holder.itemImage.setImageDrawable(drawableList[position])

        Log.d("Image - XXXXXX", drawableList.toString())
    }

    inner class ViewHolder(itemView : View): RecyclerView.ViewHolder(itemView){
        var itemImage : ImageView
        var itemTitle : TextView

        init {
            itemImage = itemView.findViewById(R.id.image_icon_component)
            itemTitle = itemView.findViewById(R.id.tv_icon_name)

        }
    }
}
1 Answers

If you want both the Drawables and their ID names, then you need to create a class to hold both, like this:

class NamedDrawable(val name: String, val drawable: Drawable) {
    override fun toString(): String = name
}

private fun getAllDrawables(): List<NamedDrawable> {
    return R.drawable::class.java.fields.mapNotNull { field ->
        ResourcesCompat.getDrawable(resources, field.getInt(null), null)
            ?.let { NamedDrawable(field.name, it) }
    }
}
Related