
Recyclerview是开发Android应用程序时显示大量列表数据的核心组件。但是,当列表数据频繁更新时,如果处理不当,可能会导致UI闪烁或完全重绘,严重影响用户体验。特别是在实时聊天应用中,如果整个聊天列表重新加载,用户会观察到明显的闪烁。
问题分析:全刷新和闪烁:Firebasee在原始代码中 Realtime 在Database的Valueeventlistenerondatachange回调中,Loadchat()方法将用于每个数据变化。LoadChat()Firebasercleradapter实例在方法内部重新创建,并调用adapter.startListening()。这种做法会导致:
- Adapter每次数据变化都会被重新创建和设置。 这相当于告诉Recyclerview所有数据都发生了变化,需要重新绘制整个列表。
- 虽然Firebasercycleradapter内部会监控数据变化,但当它重新初始化时,其内部状态会被重置,导致全面刷新。
为了解决这个问题,我们需要避免全面刷新,而是采用增量更新策略。安卓提供的Diffutil工具就是为此而生的。
引入 DiffUtil:高效的增量更新机制Diffutil是Recyclerview库提供的实用工具,用于计算两个列表之间的差异,并输出最小的更新操作集(如插入、删除、移动和更改)。RecyclerView.Adapter可以使用这些操作集进行局部更新,而不是使用notifyDatasetchanged()进行全面刷新,以避免UI闪烁,提高性能。
Diffutil的核心是通过比较新旧列表中的元素,智能地找出添加、删除或修改了哪些元素。
实现 DiffUtil 的步骤要使用Diffutil,我们需要创建一个自定义的Diffutil.实现Callback,并在Recyclerviewewiewewew.在Adapter中调用它来更新数据。
1. 定义数据模型首先,确保您的数据模型(如Chat)有一个唯一的标识符。这对于Diffutil判断两个列表项是否是同一对象至关重要。通常,我们使用数据库中的主键或唯一生成的ID。
// 示例:Chat 数据模型
public class Chat {
private String id; // 唯一的标识符,例如,Firebasekey
private String chat;
private String username;
private String profileimage;
private String dep;
private String date;
private String power;
private String quotedchat;
private String quotedname;
private long servertimestamp; // 用于排序
// 结构函数,Getter和Setter...
// 确保为id提供setter,从Firebase snapshot key设置
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
// 重写equals和hashcode方法,用于arecontentsthesame的默认比较
// 若只需要比较id,则只在areitemsthesame中比较id,arecontentsthesame中的所有内容
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Chat chat1 = (Chat) o;
return servertimestamp == chat1.servertimestamp &&
Objects.equals(id, chat1.id) &&
Objects.equals(chat, chat1.chat) &&
Objects.equals(username, chat1.username) &&
Objects.equals(profileimage, chat1.profileimage) &&
Objects.equals(dep, chat1.dep) &&
Objects.equals(date, chat1.date) &&
Objects.equals(power, chat1.power) &&
Objects.equals(quotedchat, chat1.quotedchat) &&
Objects.equals(quotedname, chat1.quotedname);
}
@Override
public int hashCode() {
return Objects.hash(id, chat, username, profileimage, dep, date, power, quotedchat, quotedname, servertimestamp);
}
}2. 创建自定义 DiffUtil.Callback
接下来,从Diffutil创建一个继承.Callback类。这个类别将负责告诉DiffUtil如何比较新旧列表中的项目。
// 与Java类似的Kotlin实现
class ChatDiffCallback(
private val oldList: List<Chat>,
private val newList: List<Chat>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
// 判断两个列表是否代表相同的逻辑实体
// 通常通过比较它们的唯一ID来确定
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// 假设Chat模型有一个独特的'id'字段
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
// 判断两个相同逻辑实体的内容是否相同
// 只有当areitemsthesame返回true时,才会被调用
// 如果您返回false,则表示该项的内容发生了变化,需要重新绑定
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// Chat模型的equals方法可以直接用在这里,如果它正确地实现了所有内容字段的比较
return oldList[oldItemPosition] == newList[newItemPosition]
// 或者更仔细地比较每个影响UI的字段
/*
val oldChat = oldList[oldItemPosition]
val newChat = newList[newItemPosition]
return oldChat.chat == newChat.chat &&
oldChat.username == newChat.username &&
oldChat.profileimage == newChat.profileimage &&
oldChat.power == newChat.power &&
oldChat.quotedchat == newChat.quotedchat &&
oldChat.quotedname == newChat.quotedname
*/
}
// 可选:若只需局部更新某些字段,这种方法可以重写
// 当areitemsthesame返回true时,但arecontententsthesame返回false
// 返回Payload对象(如Bundle或Map),指示哪些字段发生变化
// 这样,在onbindviewholder中只能更新变化的视图,而不是重新绑定所有视图
/*
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
Chat oldChat = oldList.get(oldItemPosition);
Chat newChat = newList.get(newItemPosition);
Bundle diffBundle = new Bundle();
if (!Objects.equals(oldChat.getChat(), newChat.getChat())) {
diffBundle.putString("chat", newChat.getChat());
}
// ... 检查其它字段
if (diffBundle.isEmpty()) return null;
return diffBundle;
}
*/
}3. 在 RecyclerView.Adapter 中集成 DiffUtil
您需要用自定义的Recyclerviewer替换Firebasercleradapter.Adapter,为了完全控制数据更新过程。
// 假设你有一个Myviewholder12类,与原问题中的Viewholder相同
public class MyChatAdapter extends RecyclerView.Adapter<Myviewholder12> {
private List<Chat> chatList = new ArrayList<>();
public MyChatAdapter() {
// 构造函数可以是空的或初始列表
}
// 更新列表数据的方法
public void updateChatList(List<Chat> newList) {
// 1. 创建Diffutilll创建.Calback实例
final ChatDiffCallback diffCallback = new ChatDiffCallback(this.chatList, newList);
// 2. 计算差异
final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
// 3. 更新内部数据列表
this.chatList.clear();
this.chatList.addAll(newList); // 或者直接 this.chatList = newList; 如果你确定newlist是一个新的例子
// 4. 将差异结果分配给Adapter,局部更新
diffResult.dispatchUpdatesTo(this);
}
@NonNull
@Override
public Myviewholder12 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.allchatlayout, parent, false);
return new Myviewholder12(view);
}
@Override
public void onBindViewHolder(@NonNull Myviewholder12 holder, int position) {
// 将数据绑定到视图中,类似于原问题中的onbindviewholder逻辑
Chat model = chatList.get(position);
bindChatData(holder, model, position);
}
// 如果使用getchangePayload,可以重写此方法进行局部绑定
@Override
public void onBindViewHolder(@NonNull Myviewholder12 holder, int position, @NonNull List<Object> payloads) {
if (payloads.isEmpty()) {
// 没有Payload,执行完全绑定
super.onBindViewHolder(holder, position, payloads);
} else {
// 处理Payload,进行局部更新
// 例如:
// Bundle diffBundle = (Bundle) payloads.get(0);
// if (diffBundle.containsKey("chat")) {
// holder.chat_usercomment.setText(diffBundle.getString("chat"));
// }
// ... 特定视图根据payload更新
}
}
private void bindChatData(@NonNull Myviewholder12 holder, @NonNull Chat model, int position) {
// 原始onbindviewholder中的逻辑
final String userpower = model.getPower();
final String pow = "Admin";
if (userpower != null && userpower.equals(pow)){
holder.chat_userpower.setVisibility(View.VISIBLE);
holder.chat_userpower.setText(model.getPower());
} else {
holder.chat_userpower.setVisibility(View.GONE);
}
final String quotedc = model.getQuotedchat();
// 注意:这里需要检查quotedc是否为null,而不是quotedc,而不是quotedc == null
if (quotedc == null || quotedc.isEmpty()){ // 假设空字符串也被视为没有引用
holder.quotedchatbox.setVisibility(View.GONE);
holder.quotedchatboxlayout.setVisibility(View.GONE);
holder.quotedchatdescription.setVisibility(View.GONE);
} else {
holder.quotedchatboxlayout.setVisibility(View.VISIBLE);
holder.quotedchatbox.setVisibility(View.VISIBLE);
holder.quotedchatdescription.setVisibility(View.VISIBLE);
holder.quotedchatdescription.setText("Quoted "+ model.getQuotedname() +" " + model.getQuotedchat());
}
holder.chat_usercomment.setText(model.getChat());
Picasso.get().load(model.getProfileimage()).placeholder(R.drawable.profile).into(holder.chat_userimage);
holder.chat_userdep.setText(model.getDep());
holder.chat_date.setText(model.getDate());
holder.chat_username.setText(model.getUsername());
// 监听器部分,可能需要根据实际情况进行调整,因为model是final
// 假如quote变量是Adapter或Activity/Fragment的成员,作用域需要考虑
holder.nestedchat_reply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// quote = true; // 假设quote是外部变量
// quotedname = model.getUsername();
// quoting.setVisibility(View.VISIBLE); // 假设quoting是外部Textviewiew
// quotedchat = model.getChat();
// quoting.setText("Quoting "+ quotedname + ": " + model.getChat());
// quoting.setOnClickListener(...)
}
});
}
@Override
public int getItemCount() {
return chatList.size();
}
}4. 修改数据加载逻辑
最终,为了使用Activity或Fragment中的数据加载逻辑进行修改新的自定义Adapter和Diffutil更新方法。
// 你的Activity或Fragment
public class YourChatActivity extends AppCompatActivity {
private DatabaseReference ChatRef;
private RecyclerView allchatlist;
private MyChatAdapter chatAdapter; // 使用自定义的Adapter
// ... 其它成员变量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout); // 替换您的布局文件
allchatlist = findViewById(R.id.allchatlist); // 假设你的Recyclerviewiew ID是allchatlist
// Recyclervie初始化
以上是Android Recyclerview优化:通过Diffutil实现增量更新的详细内容,请关注图灵教育的其他相关文章!