Ad

"Cannot Resolve Symbol ItemClickListener"

- 1 answer

May i know why is it showing me the error of "Cannot resolve symbol ItemClickListener"? Do i need to add library or something in order to solve this issue or i shouldn't declare it in here?

public static class FoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    private ItemClickListener itemClickListener;

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    View view;
    public FoodViewHolder (View v){
        super(v);
        view= v;
    }
    public void setName(String title){
        TextView post_title = (TextView)view.findViewById(R.id.Menu_Name);
        post_title.setText(title);
    }
    public void setImage(Context ctx, String image){
        ImageView menuImage = (ImageView) view.findViewById(R.id.Menu_Image);
        Picasso.with(ctx).load(image).into(menuImage);
    }

    @Override
    public void onClick(View v) {

    }
}
Ad

Answer

In General for RecyclerView we create an Interface for handling the click events. Unlike a normal Button Click, the RecyclerView Click events cannot be handled directly. As the RecyclerView is the Adapter(Data Provider to the View), You cannot directly handle the item clicks from here and update the view. For this you need an Separate Interface which is ItemClickListener in your case (Create an Interface file separately in your project). In that Interface you need to declare a method for example something like this

public Interface ItemClickListener{
     void onRecyclerViewItemClicked(int position);
}

Create a OnClickListener for your View(which is present over single row. Eg: image, text, etc);@Override

public void onBindViewHolder(ViewHolder holder, int position) {
    holder.myText.setOnClickListener(new View.OnClickListener() {
@Override
    public void onClick(View view) {
         itemClickListener.onRecyclerViewItemClicked(position);
         //itemClickListener is the Interface Reference Variable
    }
});
}

And in your Activity you need to implement this Interface like

public class YourActivity extends AppCompatActivity implements ItemClickListener {
     ....
     ....
     protected void onCreate(Bundle savedInstanceState) {
          ...
          ...
     }

     @Override
     public void onRecyclerViewItemClicked(int position) {
          //You will get the position of the Item Clicked over recycler view
          //You can handle as per your requirement
     }
}

Upon doing this you will listen the click event of recyclerview to the activity. Then you can handle it accordingly. If you have further doubt follow the references:
https://stackoverflow.com/a/40584425/8331006
https://stackoverflow.com/a/28304164/8331006

Ad
source: stackoverflow.com
Ad