Reputation: 25
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) {
}
}
Upvotes: 1
Views: 1090
Reputation: 2046
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
Upvotes: 1
Reputation: 1
you can set the click listener to any view you want you don't need to declare it as a seperate
yourView.setOnClickListener(this);
and in your onClick(View v) add the code that you want whenever you click the view you want for example :
if(v==imageView){
//write your code here
}
Upvotes: 0