开发的过程中遇到了如标题所述的问题 具体的图如下所示
在PopupWindow的布局中定义的recyclerview 点击之后item会变色 但是一开始在adapter中是这么写的:
holder.mItemView.setOnClickListener {
isSelected = !isSelected
mDataList[position].isSelected = isSelected
holder.mItemView.isSelected = isSelected
Log.e("PopupMultiItemAdapter", "position = $position isSelected = $isSelected mItemView.isSelected = ${holder.mItemView.isSelected}")
holder.mTextView.setTextColor(
if (isSelected) Color.WHITE
else holder.mItemView.context.resources.getColor(R.color.alphaColorCyan)
)
}
但是发现 点击之后将点击后的item滑出屏幕 再滑回来点击时 需要点击两次才能走进这个点击代码的逻辑 即便打断点调试 也没找到问题所在。于是我就换了思路想 看看setOnTouchListener这个方法 毕竟触摸事件还是优先分发的 当我在这个方法里打日志后 发现:
果然会触发两次(只DOWN和UP) 所以可以在这里做一下处理:
holder.mItemView.setOnTouchListener { v, event ->
Log.e("PopupMultiItemAdapter", "onTouch")
when (event.action) {
MotionEvent.ACTION_DOWN -> {
return@setOnTouchListener true
}
MotionEvent.ACTION_UP -> {
isSelected = !isSelected
mDataList[position].isSelected = isSelected
holder.mItemView.isSelected = isSelected
Log.e("PopupMultiItemAdapter", "position = $position isSelected = $isSelected mItemView.isSelected = ${holder.mItemView.isSelected}")
holder.mTextView.setTextColor(
if (isSelected) Color.WHITE
else holder.mItemView.context.resources.getColor(R.color.alphaColorCyan)
)
return@setOnTouchListener true
}
else -> {
return@setOnTouchListener false
}
}
}
这样就可以解决问题了~