简体   繁体   中英

How can I visually differentiate the recently clicked view in a RecyclerView from all other views?

I have a RecyclerView with photos, and I want that when a photo is clicked, it would have full opacity while all the other views would have 0.5f opacity.

I've tried many different ways, and none survives the test for the same reason. Here is an example of a simple attempt, that wouldn't have fullfiled the task very well anyway (because it only treats 2 views at the time) but would do a good job explaining the wall I'm facing:

fun changeRecyclerViewOpacity(currentPosition : Int){

    val clickedView = myLayoutManager.findViewByPosition(currentPosition)
    val previouslyClickedView = myLayoutManager.findViewByPosition(lastPosition)

    clickedView!!.alpha = 1f
    previouslyClickedView!!.alpha = 0.5f

    lastPosition = currentPosition
}

The issue I'm facing with this and with other approaches I've tried is that if (for example) the screen holds 3 images at a time, and my lastPosition is 2 and currentPosition is 10, the app crashes because the layoutManager doesn't have the view that belongs to lastPosition on screen so it can't execute the command. If I don't do that though, when the use scrolls to that view it will still have alpha at 1.0f.

If there's a completely different approach that could be taken I'd love to hear it. All I want is the clicked image to have full opacity while all the others are 0.5f.

You could try something like this in your adapter class:

var selectedPosition = 0 // You have to set this globally in the Adapter class

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val item = items.get(position)

    // Update alpha 
    var alpha: Float = 0.5f
    if(selectedPosition == position) {
        alpha = 1.0f
    }

    holder.itemView!!.alpha = alpha
}

class ViewHolder : RecyclerView.ViewHolder, View.OnClickListener {

    public ViewHolder(itemView: View) {
        super(itemView);
        itemView.setOnClickListener(this);
    }

    override
    public fun onClick(v: View) {
        // Below line is just like a safety check, because sometimes holder could be null,
        // in that case, getAdapterPosition() will return RecyclerView.NO_POSITION
        if (getAdapterPosition() == RecyclerView.NO_POSITION) return

        // Updating old as well as new positions
        notifyItemChanged(selectedPosition)
        selectedPosition = getAdapterPosition()

        // Do your another stuff for your onClick
    }
}

Let me know if this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM