android - How to hide the view of last clicked item on the recyclerview
问题描述
ViewHolder:
class HomeViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val songName: TextView = view.findViewById(R.id.txtNameSong)
val songArtist: TextView = view.findViewById(R.id.txtNameArtist)
val cardContent: CardView = view.findViewById(R.id.cardContent)
val pauseButton: ImageView = view.findViewById(R.id.pauseButton)
}
Adapter:
override fun onBindViewHolder(holder: HomeViewHolder, position: Int) {
val text = songInfoList[position]
holder.songName.text = text[0]
holder.songArtist.text = text[1]
val path = text[2]
holder.cardContent.setOnClickListener {
playMusic(path)
holder.pauseButton.visibility = View.VISIBLE
}
holder.pauseButton.setOnClickListener {
if (mediaPlayer.isPlaying) {
holder.pauseButton.setImageResource(R.drawable.play)
mediaPlayer.pause()
} else {
holder.pauseButton.setImageResource(R.drawable.pause)
mediaPlayer.start()
}
}
}
The pauseButton
appears whenever the user clicks the item on the recyclerView, and the music is played.
I want to disappear pauseButton
for the previous clicked when the user clicks on the new item and pauseButton
appear for the new entry. But, I'm unable to do this. Tell me how to do this.
Whenever I click on the new content on the recyclerView the pauseButton
should appear for the latest item and disappear for the previous item.
解决方案
You need to hold state in your RecyclerView.Adapter
Inside Adapter:
private var playingPosition: Int? = null
when a click event happens:
//Update previously position
playingPosition?.let {
models.get(playingPosition).playingState = false
notifyItemChanged(playingPosition)
}
//update new position
models.get(position).playingState = true
playingPosition = position
notifyItemChanged(position)
Also, your model should hold the playing state:`
data class Model(...: Int, ...: String, ..., playingState: Boolean)
Inside onBindViewHolder:
if (model.playingState) view.visibility = View.VISIBLE else view.visibility = VIEW.GONE
推荐阅读
- kubernetes - 本地持久卷 1 节点未找到要绑定的可用持久卷
- python - 根据行的某个值派生一个新的pandas列并应用直到下一个值再次出现
- javascript - 为什么在打印 console.log 输出之前会出现 2-3 个提示?
- php - 我无法编辑背景图像。使用宝石主题。custom.css 出错
- reactjs - 是否可以在不使用箭头函数的情况下使用 TypeScript 键入 React 函数组件?
- pyomo - pyomo 的 Couenne 选项
- c# - NullReferenceException 与 Nullable DateTime 尽管进行了空检查
- azure - LUIS 通话限制
- javascript - 如何在不接触 index.html 的情况下将外部 javascript 标签添加到 Ember JS 应用程序?
- python - 将一列合并并与 (2,N) 数组的另一列相加