Neww
hacker98
java
a year ago
3.3 kB
4
Indexable
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ConversationViewHolder> {
private List<Conversation> conversationList;
private Context context;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public ConversationAdapter(Context context, List<Conversation> conversationList) {
this.context = context;
this.conversationList = conversationList;
// Sắp xếp danh sách theo thời gian khi khởi tạo adapter
sortConversationsByTime();
}
@NonNull
@Override
public ConversationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_conversation, parent, false);
return new ConversationViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ConversationViewHolder holder, int position) {
Conversation conversation = conversationList.get(position);
holder.nameTextView.setText(conversation.getName());
holder.lastMessageTextView.setText(conversation.getLast_mess());
holder.timeTextView.setText(conversation.getLast_mess_time());
}
@Override
public int getItemCount() {
return conversationList.size();
}
// Hàm để cập nhật danh sách cuộc hội thoại mới và sắp xếp
public void updateConversations(List<Conversation> newConversationList) {
this.conversationList = newConversationList;
sortConversationsByTime(); // Sắp xếp theo thời gian
notifyDataSetChanged(); // Cập nhật lại giao diện
}
// Sắp xếp danh sách cuộc hội thoại theo thời gian tin nhắn cuối cùng
private void sortConversationsByTime() {
Collections.sort(conversationList, new Comparator<Conversation>() {
@Override
public int compare(Conversation c1, Conversation c2) {
try {
Date date1 = dateFormat.parse(c1.getLast_mess_time());
Date date2 = dateFormat.parse(c2.getLast_mess_time());
return date2.compareTo(date1); // Sắp xếp giảm dần theo thời gian
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
});
}
public static class ConversationViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView, lastMessageTextView, timeTextView;
public ConversationViewHolder(@NonNull View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textViewName);
lastMessageTextView = itemView.findViewById(R.id.textViewLastMessage);
timeTextView = itemView.findViewById(R.id.textViewTime);
}
}
}Editor is loading...
Leave a Comment