简体   繁体   中英

Recyclerview - cardview onclick change image?

I have an app that as a Recyclerview --> Cardview, in the cardvie I have text and an image, and what i'm trying to do is to onclick change the image of the cardview;

this is the code that handles the click for the card view; is there a way to change the img on click, recyclerview has around 20 cardviews.

Activity

   @Override
    public void onItemClick(int position) {
        myAdapter click = myList.get(position);
        String name = click.getName();

        Log.e(TAG, "Position: " + position);
    }

Adapter

public class ViewHolder2 extends RecyclerView.ViewHolder {
        public TextView fId;
        public TextView fName; 
        public ImageView fImageButton;

        public ViewHolder2(@NonNull View itemView) {
            super(itemView);
            fId       = itemView.findViewById(R.id.id);
            fName     = itemView.findViewById(R.id.name);
            fImageButton = itemView.findViewById(R.id.micd_item_icon); 

            itemView.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        fListener.onItemClick(position);
                        Log.e(TAG, "D");
                    }

                }
            });
        }
    }



     public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        myAdapter currentItem = myList.get(position);

        String id       = currentItem.getfId();
        String name     = currentItem.getfName(); 

        holder.fId.setText(id);
        holder.fName.setText(name);  
        holder.fImageButton.setImageResource(R.drawable.ic_cloud_download); 
    }
  1. Give ID to your CardView in your layout.

  2. Make a findViewById() call in your ViewHolder .

  3. In onBindViewHolder of your RecyclerView.Adapter , set an OnClickListener to the CardView .

  4. In onClick(View v) of this CardView , set the image to ImageView.

    //If you're loading image from list Glide.with(context).load(list.get(position).getImageUrl()).into(holder.imageView);

    //If you just want to set an image from your drawables holder.imageView.setImageResource(context.getResources().getDrawable(R.drawable.icon));

I'm unable to format the above stuff properly because editor is bugged out for me for some reason.

Edits are welcome.

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