Reputation: 877
I am making a conventional chat activity that styles messages based on whether or not a the Firebase ID of a message's author is the logged in user. The messages are given the the appropriate appearance when the activity is initially started and views are created, but when new messages are added, messages are being given the wrong appearance. Some older messages are even being switched from one style to despite the author information being the same:
User 1:
User 2:
onBindViewHolder Code:
@Override
public void onBindViewHolder(@NonNull DMViewHolder holder, int position) {
Message message = messageList.get(position);
String signedInUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
boolean isSignedInUser = message.getAuthorUID().equals(signedInUserID);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
holder.message.setText(message.getMessage());
holder.date.setText(simpleDateFormat.format(message.getTimestamp()));
if (isSignedInUser) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_END);
holder.textContainer.setLayoutParams(params);
} else {
holder.textContainer.setBackgroundResource(R.drawable.partner_message_text_background);
}
}
Upvotes: 0
Views: 40
Reputation: 54204
The problem is in this code:
if (isSignedInUser) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_END); holder.textContainer.setLayoutParams(params); } else { holder.textContainer.setBackgroundResource(R.drawable.partner_message_text_background); }
You are only changing the LayoutParams
when your if
condition evaluates to true. You need to set it back when the if
evaluates to false. Similarly, you either want to call setBackgroundResource()
in both branches of the if
statement, or you want to call it outside the if
.
if (isSignedInUser) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_END);
holder.textContainer.setLayoutParams(params);
holder.textContainer.setBackgroundResource(R.drawable.some_other_background);
} else {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_START);
holder.textContainer.setLayoutParams(params);
holder.textContainer.setBackgroundResource(R.drawable.partner_message_text_background);
}
When working with ListView or RecyclerView, you have to remember to always update every part of the view every time it is called... updating only parts of the view will cause problems like this one when views are recycled.
Upvotes: 2