首页 > 解决方案 > 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.

标签: androidkotlinandroid-recyclerviewandroid-adapter

解决方案


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

推荐阅读