In Recycle view how to Highlight always one adapter item with the click and without click

前端 未结 4 1699
刺人心
刺人心 2021-01-29 14:24

Here I clicked on the item to change item background and color. I\'ve stored the clicked item value in the database and change the layout color and text color and recreating the

4条回答
  •  庸人自扰
    2021-01-29 14:52

    Note: onBindViewHolder() is not a place to implement the click listeners, but I am just providing you the logic for how to implement single selection in recyclerView.

    Now lets jump to the solution, simply follow the below tutorial and change the variable, fields, and background according to your need, you have to implement the below method in onBindViewHolder() method of RecyclerView

    First, initialize the lastClickedPosition and isclicked

        int lastPositionClicked = -1;
         boolean isClicked = false;
    
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
    
        holder.YOUR_VIEW.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // store the position which you have just clicked and you will change the background of this clicked view
                lastPositionClicked = position;
                isClicked = true;
    
                // need to refresh the adapter
                SlabAdapter.this.notifyDataSetChanged();
            }
        });
    
        // only change the background of last clicked item 
        if (isClicked && position == lastPositionClicked) {
            // change clicked view background color
        } else {
            // otherwise set the default color for all positions
    
        }
    }
    

    let me know if this works.

提交回复
热议问题