问题
I am trying to load a recycler view that lists cards, each card has four elements. two text views(posttext, score are the id) and two buttons(minusOne and plusOne).
The code below loads the textview's content and buttons properly on all cards.
I try to implement the following behavior.
onbuttonclick of plusOne button, the score will be changed and the minusOne button is hidden.
The strange part is, the scores get updated properly on respective cards. But the hiding part appears to happen in multiple cards when the action is performed on one card.(every n+5th card). How do I fix this? Where am I going wrong? Thank you.
P.S : Suggest title edit
@Override
public void onBindViewHolder(
final MyViewHolder viewHolder, final int position) {
ParseObject model = items.get(position);
viewHolder.posttext.setText(model.getString("postText"));
viewHolder.score.setText(Integer.toString(model.getInt("score")));
viewHolder.plusOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ParseObject model = items.get(position);
final int score = model.getInt("score");
model.increment("score", 1);
model.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if(e==null)
{
viewHolder.score.setText(Integer.toString(score+1));
viewHolder.minusOne.setVisibility(View.GONE);
}
else{
e.printStackTrace();
}
}
});
}
});
回答1:
You need to make Arraylist of booleans for the minus button you can set it in your model or in the adapter whatever you want, this arraylist will contains the status of the button so it will be true by default unless the user clicked so it will change to false, and after updating it just notify the adapter by notifyDataSetChanged() it will update the shown views as the array of booleans.
@Override
public void onBindViewHolder(
final MyViewHolder viewHolder, final int position) {
ParseObject model = items.get(position);
viewHolder.posttext.setText(model.getString("postText"));
viewHolder.score.setText(Integer.toString(model.getInt("score")));
if (miusButtonStatus.get(position)) {
viewHolder.minusOne.setVisibility(TextView.VISIBLE);
} else {
viewHolder.minusOne.setVisibility(TextView.GONE);
}
viewHolder.plusOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ParseObject model = items.get(position);
final int score = model.getInt("score");
model.increment("score", 1);
model.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if(e==null)
{
viewHolder.score.setText(Integer.toString(score+1));
miusButtonStatus.get(position) = false;
notifyDataSetChanged();
}
else{
e.printStackTrace();
}
}
});
}
});
来源:https://stackoverflow.com/questions/30338314/recyclerview-onbindviewholder-onclicklistener-behavior