【问题标题】:Sort a Custom Listview Adapter by Date按日期对自定义 Listview 适配器进行排序
【发布时间】:2017-06-25 11:46:08
【问题描述】:

我想用 Firebase 编写一个 ChatApp。现在我正在显示与我聊天的用户。但现在我希望它们按我正在使用的日期字符串排序: 例如:21-06-2017 17:20。应该从最晚的时间到最早的时间排序。

我的适配器:

public class ChatAdapter extends ArrayAdapter<String> {

private Activity context;
private List<Chats> chatsList = new ArrayList<>();

public ChatAdapter(Activity context, List<Chats> chatsList) {
    super(context, R.layout.abc_main_chat_item);
    this.context = context;
    this.chatsList = chatsList;
}

@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.abc_main_chat_item, null, true);

    TextView tvusername = (TextView) listViewItem.findViewById(R.id.group_name);
    TextView tvuid = (TextView) listViewItem.findViewById(R.id.useruid);
    TextView tvlastmessage = (TextView) listViewItem.findViewById(R.id.latestMessage);
    TextView tvlastmessagetime = (TextView) listViewItem.findViewById(R.id.latestMessageTime);
    ImageView ivphoto = (ImageView) listViewItem.findViewById(R.id.profileImg);

    tvusername.setText(chatsList.get(position).getUsername());
    tvlastmessage.setText(chatsList.get(position).getLastMessage());
    tvlastmessagetime.setText(chatsList.get(position).getLastMessageTime());
    tvuid.setText(chatsList.get(position).getUseruid());
    Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(ivphoto);

    listViewItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, Chat_Room.class);
            i.putExtra("room_name", chatsList.get(position).getUsername());
            i.putExtra("room_uid", chatsList.get(position).getUseruid());
            context.startActivity(i);

        }
    });

    listViewItem.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.abcd_listview_alertdia_layout);
            ArrayList<String> list_of_chats = new ArrayList<>();
            final ArrayAdapter<String> arrayAdapter;
            arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_of_chats);

            list_of_chats.add(0, "Chatverlauf mit "+ chatsList.get(position).getUsername()+" löschen?");
            list_of_chats.add(1, "Profil von "+chatsList.get(position).getUsername()+" anschauen");
            arrayAdapter.notifyDataSetChanged();
            final ListView lv = (ListView) dialog.findViewById(R.id.lv);
            lv.setAdapter(arrayAdapter);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position2, long id) {
                    if (position2 == 0) {
                        dialog.dismiss();
                        AlertDialog.Builder alert = new AlertDialog.Builder(context);
                        alert.setTitle("Chatverlauf mit "+chatsList.get(position).getUsername()+" löschen?")
                                .setMessage("Du kannst das Löschen nicht rückgängig machen. Bist du dir sicher?")
                                .setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                })
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(chatsList.get(position).getUseruid()).setValue(null);
                                        FirebaseDatabase.getInstance().getReference().child("chats").child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("messages").child(chatsList.get(position).getUseruid()).setValue(null);
                                    }
                                }).setCancelable(true)
                                .show();
                        lv.setAdapter(arrayAdapter);
                        arrayAdapter.notifyDataSetChanged();
                    }
                    if (position2 == 1) {
                        Intent intent = new Intent(context, ViewContact.class);
                        intent.putExtra("useruid", chatsList.get(position).getUseruid());
                        context.startActivity(intent);
                    }
                }
            });
            dialog.show();
            return true;
        }
    });

    ivphoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.abcd_profile_pic_dialog_layout);
            ImageView imageView = (ImageView) dialog.findViewById(R.id.alertImage);
            TextView textView = (TextView)dialog.findViewById(R.id.alertdialogtv);
            ImageView message = (ImageView)dialog.findViewById(R.id.alertMessage);
            ImageView profile = (ImageView)dialog.findViewById(R.id.alertProfile);
            profile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ViewContact.class);
                    intent.putExtra("useruid", chatsList.get(position).getUseruid());
                    context.startActivity(intent);
                    dialog.dismiss();
                }
            });
            message.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), Chat_Room.class);
                    intent.putExtra("room_name", chatsList.get(position).getUsername());
                    intent.putExtra("room_uid", chatsList.get(position).getUseruid());
                    context.startActivity(intent);
                }
            });
            Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(imageView);
            textView.setText(chatsList.get(position).getUsername());
            dialog.setCancelable(true);
            dialog.show();
        }
    });

    return  listViewItem;
}

这就是我获得 ArrayLists 的方式:

`for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    username.add(snapshot.child("roomname").getValue().toString());
                    photoURL.add(snapshot.child("photoURL").getValue().toString());
                    lastmessage.add(snapshot.child("lastMessage").getValue().toString());
                    lastmessagetime.add(snapshot.child("lastMessageTime").getValue().toString());
                    useruid.add(snapshot.child("userUiD").getValue().toString());
                }

                ChatAdapter chatAdapter = new ChatAdapter(getActivity(), username, useruid, photoURL, lastmessage, lastmessagetime);
                listView.setAdapter(chatAdapter);`

但是我怎样才能将它作为 List 传递? 如何将它们添加到列表中?

甚至可以排序吗?

我希望你们能帮助我:) 谢谢。

【问题讨论】:

    标签: android sorting listview android-arrayadapter


    【解决方案1】:

    这当然是可能的。 但首先,您的数据结构看起来很奇怪且不切实际。

    您的消息在单个数组中传递,这使得它非常复杂:

    ArrayList&lt;String&gt; username, ArrayList&lt;String&gt; useruid, ArrayList&lt;String&gt; photoURL, ArrayList&lt;String&gt; lastmessage, ArrayList&lt;String&gt; lastmessagetime

    最好有一个Messageobjects 列表,其中一个消息对象包含单个项目,如下所示:

    public class Message {
    
       String username;
       String useruid;
       String photoURL;
       String message;
       Date timestamp;
       //...getter and setter
    }
    

    更好的办法是让Message 对象只包含一个userId、messageText 和timeStamp。这就是你所需要的。

    然后您可以将List&lt;Message&gt; messages 传递给您的适配器。

    要对消息列表进行排序,您可以实现 Comparable 类,然后您可以在其中以您喜欢的方式对对象进行排序。

    public class Message implements Comparable<Message>{
    
       String username;
       String useruid;
       String photoURL;
       String message;
       Date timestamp;
    
       @Override
       public int compareTo(@NonNull Message o) {
           return this.timestamp.compareTo(o.timestamp)
       }
    }
    

    如果您已将 Comparable 添加到您的 Messageclass,您可以使用 Collections.sort(messages); 对列表进行排序。

    看看java comparable,有various examples。也看看这个stackoverflow answer.

    编辑:回答您的附加问题:

    在您的情况下,当您获取元素时,您会执行以下操作:

    List<Message> messages = new ArrayList<Message>();
    
    for(DataSnapshot snapshot : dataSnapshot.getChildren()){
         Message message = new Message();
         message.setName(snapshot.child("roomname").getValue().toString());
         …
         //set all your properties and then add that object to the messages list
         messages.add(message);
         }
    Collections.sort(messages); // sort the message list
    ChatAdapter chatAdapter = new ChatAdapter(getActivity(), messages);
    listView.setAdapter(chatAdapter);
    

    【讨论】:

    • 您可以像当前传递所有列表一样传递它。我扩展了我的答案并链接了关于该主题的另一个 SO 答案。
    • 对不起。但我不知道如何向 List 添加内容。你能用 ArrayList 更改我上次的编辑并告诉我如何添加一些东西吗?
    • 当我这样做时,它不起作用:chats.setUsername(snapshot.child("roomname").getValue().toString()); chats.setPhotoURL(snapshot.child("photoURL").getValue().toString()); List&lt;chatapp.chatapp2.Chats.Chats&gt; chatsList = new ArrayList&lt;&gt;(); chatsList.add(chats); ChatAdapter chatAdapter = new ChatAdapter(getActivity(), chatsList); listView.setAdapter(chatAdapter);
    • 所以.. 它现在应该可以工作了。当我记录名称时,我会在 Logcat 中得到一个结果。但是这些项目不会出现在列表视图中。您可以在问题中看到我更新的适配器。你能找到错误吗?因为我找不到。对我来说它应该工作..
    • 这个问题是关于如何为您的适配器排序列表。我想那一个答案?也许最好关闭这个问题并转移到一个新问题,您可以在其中分享您当前的代码和新问题。
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 2022-10-23
    • 2012-03-10
    • 2015-02-27
    • 2012-07-23
    • 2012-02-06
    相关资源
    最近更新 更多