Android RecyclerView with OnClick Event

 Using RecyclerView is preferred over ListView to display lists. Unlike ListView, we do not add the OnItemClickListener directly to RecyclerView. Instead, we set onClickListener inside the ViewHolder.

ViewHolder interprets the layout xml file, which may contain multiple UI components. Therefore, we can

  1. implement onClickListener to the ViewHolder only

  2. implement onClickListener to an individual component in the ViewHolder

Set OnClickListener inside ViewHolder

Inside the constructor of MyViewHolder, I assign OnClickListener to the ViewHolder itself and the button inside this VIewHolder. When I click the button, the button will catch the click event prior to the ViewHolder. Therefore, method onClick() of the button onClickListener is executed and method onClick() of ViewHolder onLickListener is not invoked.

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
   public final TextView nameText;
   public final ImageButton button;

   public MyViewHolder(View view,){
       super(view);
       nameText = (TextView) view.findViewById(R.id.name);
       button = (ImageButton) view.findViewById(R.id.button);
       button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               .....
           }
       });
       //define click listener for ViewHolder's View
       view.setOnClickListener(this);
       
   }


   @Override
   public void onClick(View v) { ....... }
}

Passing computation result outside

If we want to pass the result outside ViewHolder, i.e the Fragment that holds the RecyclerView, we can define a customer interface and pass the instanced Object of this interface into the ViewHolder.

public interface MyCustomInterface {
   public void onClickResult(View v, int position);
}


We instantiate an object implementing MyCustomInterface in a Fragment. This object is passed to the RecyclerView.Adapter and we add a variable in the ViewHolder to reference this object. We invoke the custom method of this object in the method onClick(). Therefore, when we click the ViewHolder each time, the object instance inside the Fragment can handle the result.

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
   ....
   MyCustomInterface myInterfaceObject;

   public MyViewHolder(View view, MyCustomInterface myInterfaceObject){
       super(view);
       ....
       //define click listener for ViewHolder's View
       this.myInterfaceObject = myInterfaceObject;
   }


   @Override
   public void onClick(View v) { myInterfaceObject.onClickResult(v, getBindingAdapterPosition()); }
}

留言

此網誌的熱門文章

Use okhttp to download file and show progress bar

Download File into app specific storage with Retrofit

Unzipp file with Zip4j library