NOTE: I solved the problem while I was writing the question so no answers needed. Still sharing this with the answer so that someone experiencing the same can benefit from it.
I have a recycler view which contains image and 2 textViews. I want to rotate the image when it is clicked but some strange things happen:
Sometimes, the image is not rotated. And sometimes, I see some images rotated even though I didn't click on them.
The code for onClickListener:
arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAnswer(getAdapterPosition(), arrow);
}
});
The method it is calling:
private void showAnswer(int adapterPosition, ImageView arrow){
Info info = infoList.get(adapterPosition);
info.setExpanded(!info.isExpanded());
if(!info.isExpanded()){
arrow.setRotation(90);
}
else{
arrow.setRotation(0);
}
notifyItemChanged(adapterPosition);
}
Note that, I also change the visibility of one of my textViews at the same time which works perfectly fine.
I caught my mistake while I was writing the "I also change the visibility of one of my textViews" part of the question. Where was I changing it? Not in the onClickListener. It was in the onBindViewHolder method. Therefore, removing the if-else statements from onClick and adding the last line in the following method solved my problem:
@Override
public void onBindViewHolder(@NonNull RuleViewHolder holder, int position) {
Info info = infoList.get(position);
holder.questionTextView.setText(info.getQuestion());
holder.answerTextView.setText(info.getAnswer());
boolean isExpanded = infoList.get(position).isExpanded();
holder.expandableLayout.setVisibility(isExpanded ? View.VISIBLE : View.GONE);
holder.arrow.setRotation(isExpanded ? 90 : 0);
}