RecyclerView 适配器无法识别 ImageView 中的当前可绘制对象

RecyclerView adapter not recognising current drawable in ImageView

我正在尝试让我的应用程序使用 if 语句并检测特定的可绘制对象是否设置为 ImageView。但是,if 部分由于某种原因永远不会执行(总是 else 部分)。我真的不明白为什么当我在 if 语句中使用 constantState 时这不起作用。

class MyRVAdapter(private val myList: ArrayList<Facility>): RecyclerView.Adapter<MyRVAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return myList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.mIVExpandCollapse.setOnClickListener {
            if (holder.mIVExpandCollapse.drawable.constantState == ContextCompat.getDrawable(holder.mIVExpandCollapse.context, R.drawable.ic_keyboard_arrow_down)!!.constantState) {
                    Toast.makeText(holder.mIVExpandCollapse.context, "Hi there! This is a Toast.", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(holder.mIVExpandCollapse.context, "Hi there! This is not a Toast.", Toast.LENGTH_LONG).show()
            }
        }
    }

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

    class ViewHolder (itemView : View):RecyclerView.ViewHolder(itemView) {
        val mIVExpandCollapse = itemView.findViewById<ImageView>(R.id.iv_expandcollapsearrow)!!
    } 
}

尝试在列表的每个项目中维护一个名为 isExpanded 的布尔值。使用它检查扩展,而不是视图,因为在滚动列表时,视图会被回收并且您想要的状态也会丢失。这是这个想法的实现:

Facility.kt

data class Facility(

        /* Other fields are here, */

        var isExpanded: Boolean = false
)

MyRVAdapter.kt

class MyRVAdapter(private val myList: ArrayList<Facility>) : RecyclerView.Adapter<MyRVAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return myList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = myList[position]
        holder.mIVExpandCollapse.setOnClickListener {
            if (item.isExpanded) {
                Toast.makeText(holder.mIVExpandCollapse.context, "Hi there! This is an expanded item.", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(holder.mIVExpandCollapse.context, "Hi there! This is an collapsed item.", Toast.LENGTH_LONG).show()
            }
            item.isExpanded = !item.isExpanded
        }
    }

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

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mIVExpandCollapse = itemView.findViewById<ImageView>(R.id.iv_expandcollapsearrow)!!
    }

}