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

时间:2019-01-20 13:07:01

标签: android kotlin android-imageview android-drawable android-resources

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

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

1 个答案:

答案 0 :(得分:1)

尝试在列表的每个项目中保留一个名为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)!!
    }

}