我正在进行一个常规的聊天活动,该活动基于消息作者的Firebase ID是否是登录用户来设置消息的样式。在最初启动活动和创建视图时,将为消息赋予适当的外观,但是在添加新消息时,将为消息赋予错误的外观。尽管作者信息相同,一些较旧的消息甚至已从一种样式切换为:
用户1:
用户2:
onBindViewHolder代码:
@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);
}
}
答案 0 :(得分:2)
问题出在此代码中:
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); }
仅当您的LayoutParams
条件评估为true时,才更改if
。当if
的计算结果为false时,您需要将其重新设置。同样,您要么要在setBackgroundResource()
语句的两个分支中调用if
,要么要在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);
}
使用ListView或RecyclerView时,您必须记住每次调用时都要始终更新视图的每一部分...仅更新视图的一部分会在回收视图时引起类似这样的问题。