Reputation: 562
Last night I was coding and got help on StackOverflow with a onClick event. I finally sorted it out but had to do it differently than the tutorials on the internet and I can't seem to get it working on the right way.
Currently, I have an adapter which has an interface that can be called from my activity. However normally you should implement View.OnClickListener in your ViewHolder and override the onClick method. But the method doesn't get executed, whatever I try to do. Even though I set clickable to true and setOnClickListener on the current ItemView.
My working solution is to add a clickListener in the onBindViewHolder which executes a function in my interface, which is then executed in my activity. Which works.
So anyone, has ANY idea of what could be preventing the onClick from executing? No errors, no warnings... nothing. And maybe a second side question: is the method I'm doing right now a bad method or should it be done with the onClick in the viewHolder?
My viewHolder
public class ParkingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView parkingName;
TextView parkingCapacity;
ParkingViewHolder(View itemView) {
super(itemView);
itemView.setClickable(true);
itemView.setOnClickListener(this);
cv = (CardView)itemView.findViewById(R.id.cv);
parkingName = (TextView)itemView.findViewById(R.id.parkingName);
parkingCapacity = (TextView)itemView.findViewById(R.id.parkingCapacity);
}
@Override
public void onClick(View v) {
System.out.println("Doesnt get executed");
// this should work but the system.out doesn't get executed either so problems should be somewhere else
if(clickListener != null) {
clickListener.itemClicked(v, getLayoutPosition(), parkings.get(getLayoutPosition()));
}
}
}
Upvotes: 0
Views: 1605
Reputation: 12861
Try this.
public class ParkingViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView parkingName;
TextView parkingCapacity;
ParkingViewHolder(View itemView) {
super(itemView);
itemView.setClickable(true);
itemView.setOnClickListener(this);
cv = (CardView)itemView.findViewById(R.id.cv);
parkingName = (TextView)itemView.findViewById(R.id.parkingName);
parkingCapacity = (TextView)itemView.findViewById(R.id.parkingCapacity);
parkingName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("executed");
}
});
}
}
Upvotes: 4