I have implemented a recyclerView
in my project.
I have a Button
in my recyclerView
row
. The code for my each row of recyclerView
is like this:
savedmessage_custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Dummy text" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
android:visibility="gone"/>
</LinearLayout>
The visibility of button is gone
. I want to change the visibility of this button to 'visible' when someone clicks on the message
textView
above it. I implemented a simple onClickLiestener()
on the message (textView)
and changed the visibility of button
on click of the message
. I knew that wasn't going to work but I wanted to see the results. The results are weird. If I click on the textView of row 1, the button of row 7,17,19 etc also becomes visible. I can guess this might be coz of caching of the viewHolder.
MyViewHolder is something like this:
class MyViewHolder extends RecyclerView.ViewHolder {
TextView message;
public MyViewHolder(final View itemView) {
super(itemView);
message = (TextView) itemView.findViewById(R.id.message);
message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemView.findViewById(R.id.button).setVisibility(View.VISIBLE);
}
});
}
}
Can someone guide me how can I change the visibility of a button, of a perticular row only, of my recyclerView?
Move the click logic away from the ViewHolder:
class MyViewHolder extends RecyclerView.ViewHolder {
TextView message;
Button button;
public MyViewHolder(View itemView) {
super(itemView);
message = (TextView) itemView.findViewById(R.id.message);
button = (Button) itemView.findViewById(R.id.button);
}
}
and place it inside the method onBindViewHolder of your adapter:
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.button.setVisibility(View.GONE);
holder.message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
holder.button.setVisibility(View.VISIBLE);
}
});
}
ViewHolder is reused by the RecyclerView, that's why you are seeing the button visible in other rows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With