简体   繁体   中英

Adding an onClick to a part of a RecyclerView item

I've been working on an online shop type of application, and I've hit a bump: I've been tasked to add a favorites system, but I can't figure out how to enable pressing a button that's part of the RecyclerView item to add it to favorites. (In this case, the heart, which is supposed to turn to a full heart when clicked) RecyclerView的图像

Add a boolean value for favourite in your list . Initially , keep it false . You need to have two drawables , one for selected state and another for unselected state .

In your onBindViewHolder , set the drawable on runtime on the basis of above condition .

 if(list.isfav)
 { 
   holder.ivHeart.setImageDrawable(ContextCompat.getDrawable(context,(R.drawable.selected));
  }else{
   holder.ivHeart.setImageDrawable(ContextCompat.getDrawable(context,(R.drawable.unselected));
  }

Put onClick on this ivHeart eg:

holder.ivHeart.setOnClickListener(v -> {
                if(list.isfav) {
                 list[adapterPosition].isfav = false;
                }else{
               list[adapterPosition].isfav = true;
                }
               notifyItemChanged(adapterPosition);
           });

Dont forget to notify the item while changing item .

In your RecyclerView adapter's onBindViewHolder() method, add click listener to your view and change the drawable programmatically.

The code will be something like this

@Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);

        holder.your_like_imageview.setOnClickListener{
        holder.your_like_imageview.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.something_else));
       };



    }

I'm assuming you're using an ImageView for the heart. What you can do is set a click listener on that ImageView and process that click.

An ideal way to do this would be to use an interface to handle click events that you pass to the Adapter.

However you could do something like this in the onBindViewHolder method:

imageView.setOnClickListener { // depending your logic change the tint for the icon or the drawable onClick(data[position], addToWishlist) notifyDataSetChanged() }

The onClick method will receive the particular item and a flag to add or remove it from the wishlist:

fun onClick(data: Data, addToWishlist: Boolean) { // you can perform the addition/ deletion from the wishlist here }

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