简体   繁体   中英

onclicklistener on the specific item of the recyclerview in android

I am going to ask very basic question, but i am stuck in it for a long time.

after card view there is an recycleview which has 2 images in each row. now i want to create the click listener on the images rather than the recycleview.

the corresponding layout(layout_main.xml) of this activity(MainActivity.java) contain only recyclerview. the elements of each row is in another layout(layout_images.xml). i am getting the images from layout_images.xml and inflate them in the adapter class(Adapter.java).

now how to put action listener on the images only.

secondly, i want to get the image on which i clicked. how to get that. like, when we click on a view we create some method as

public void onClick(View view){
    // some code here
}

where view is the object on which we clicked. in my case how to get the image on which i clicked. using type cast it might be throw an exception when user doesnot click on image.

Multiple onClick events inside a recyclerView:

public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

    public ImageView iconImageView;
    public TextView iconTextView;

    public MyViewHolder(final View itemView) {
        super(itemView);

        iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
        iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);
        // set click event
        itemView.setOnClickListener(this);
        iconTextView.setOnClickListener(this);
        // set long click event
        iconImageView.setOnLongClickListener(this);
    }

    // onClick Listener for view
    @Override
    public void onClick(View v) {    
        if (v.getId() == iconTextView.getId()) {
            Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
        }
    }


    //onLongClickListener for view
    @Override
    public boolean onLongClick(View v) {    
        final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
        builder.setTitle("Hello Dialog")
            .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

        builder.create().show();
        return true;
    }
}

To get which item was clicked you match the view id ievgetId() == yourViewItem.getId()

You have to set onClickListener to the ImageView s inside the onBindViewHolder method, refer the following LOCs for reference(code to be inside onBindViewHolder method)

holder.imageView1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //put your code for first imageview here
    }
});
holder.imageView2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //put your code for second imageView here
    }
});

In Recycle View Holder , Write your onclick listener code inside

    @Override
    public void onBindViewHolder(CardHolder holder, final int position) {
       holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //TODO
            }
        }
   }

implement the View.OnClickListener in your ViewHolder class and implement the onClick method. Then set the click listener for your ImageView to this click listener. Add the required functionality in the onClick method. If you want to implement the click functionality in other class simply create an interface and declare a click method in it. You can implement this method in the activity/fragment that contains this RecycleView. Then from your view holders onClick method you can invoke the interface method.

You can check with tag or it of element like this:

public void onClick(View view){
if(view.getId() == image1.getId())
{

}else if(view.getId() == image2.getId())
{}

}

First of all set onclickListener to each view you want to be clicked. Good place to do it in viewHolderConstructor. eg

  public class GalleryManyViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.im_img) RoundedCornersImageView imImg;
    @BindView(R.id.tv_title) MyTextView tvTitle;
    @BindView(R.id.tv_label) MyTextView tvLabel;
    @BindView(R.id.tv_date) MyTextView tvDate;
    @BindView(R.id.im_gallery_one) RoundedCornersImageView imGalleryOne;
    @BindView(R.id.im_gallery_two) RoundedCornersImageView imGalleryTwo;
    @BindView(R.id.im_gallery_three) RoundedCornersImageView imGalleryThree;
    @BindView(R.id.im_gallery_four) RoundedCornersImageView imGalleryFour;
    @BindView(R.id.tv_more) MyTextView tvMore;
    @BindView(R.id.root) RelativeLayout root;

    public GalleryManyViewHolder(View view) {
      super(view);
      ButterKnife.bind(this, view);
      view.setOnClickListener(onClickListener);
      imGalleryOne.setOnClickListener(onClickListener);
      imGalleryTwo.setOnClickListener(onClickListener);
      imGalleryThree.setOnClickListener(onClickListener);
      imGalleryFour.setOnClickListener(onClickListener);
      view.setTag(this);

    }

Generally you do not need to make anything specific with those view, like setting tags (Also some usefull libraries like Glied, which sets its own tags to imageviews will malfunction if you set you own tag. In on clickListener find adapter position of the view to be able to retrive the corresponding data

View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override public void onClick(View v) {
      View view = v;
      View parent = (View) v.getParent();
      while (!(parent instanceof RecyclerView)){
        view=parent;
        parent = (View) parent.getParent();
      }
      int position = recyclerView.getChildAdapterPosition(view);
}

as described here Then but checking views id, evaluete what you want to do

switch (v.getId()) {
            case R.id.im_gallery_one: {
              p = 0;
            }
            break;
            case R.id.im_gallery_two: {
              p = 1;
            }
            break;
            case R.id.im_gallery_three: {
              p = 2;
            }
            break;
            case R.id.im_gallery_four: {
              p = 3;
            }
            break;
          }

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