我正在尝试让我的应用使用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)!!
}
}
答案 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)!!
}
}