Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kevin Faust
15,353 PointsOnClickListener with RecyclerView
Hello,
Im doing the Android Activity Lifecycle and I tried to do it with recyclerview. However Im not sure how to add a onclicklistener to a specific element. There are two buttons and when we click them, we want the number counter to go up and down.
Since we need access to the element's position, I put an onclick listener under the bind method:
@Override
public void onBindViewHolder(final listViewHolder holder, final int position) {
holder.bind(mHoles[position]);
holder.mRemoveStrokeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int updatedStrokeCount = mHoles[position].getStrokeCount() - 1;
if (updatedStrokeCount < 0) updatedStrokeCount = 0;
mHoles[position].setStrokeCount(updatedStrokeCount);
holder.mStrokeCount.setText(updatedStrokeCount + "");
}
});
holder.mAddStrokeCount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int updatedStrokeCount = mHoles[position].getStrokeCount() + 1;
mHoles[position].setStrokeCount(updatedStrokeCount);
holder.mStrokeCount.setText(updatedStrokeCount + "");
}
});
}
It seems logical but there's probably more to it as my app keeps crashing
Thanks,
Kevin