可绘制对象列表中的可绘制对象名称 kotlin

Drawables name in a list of all drawables kotlin

这是我的class,在这里我调用了所有的Drawables,但是我做的那一刻“drawableList.toString()”return名称为“android.graphics.drawable.bitmap@65vd6f5”,我希望 return 为“R.drawable.icon_outline_airplane”。有人可以帮我吗?

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)

        }
    }
}

如果您同时想要 Drawable 和它们的 ID 名称,那么您需要创建一个 class 来保存两者,如下所示:

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