如何在 Recycler View 中显示最近的聊天消息?

How to display most recent chat message in Recycler View?

我对 Android/Java 开发还很陌生。我正在从事一个涉及聊天的项目 activity。

我希望 activity 自动滚动到聊天屏幕底部(最近的聊天消息)。

我尝试使用 Toast 显示 getItem 计数 - 我能够验证我可以正确获取 Recyclerview 项目的 int 位置。但是,我正在努力使用 ScrollToPosition 或 SmoothScroltoPosition 来获得我想要的结果。

关于如何自动滚动到我最近的聊天项目有什么想法吗?

下面是我的聊天 activity:

public class ChatActivity 扩展 AppCompatActivity {

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mChatAdapter;
private RecyclerView.LayoutManager mChatLayoutManager;
private  String currentUserID, matchId, chatId;

private EditText mSendEditText;
private Button mSend;

DatabaseReference mDatabaseChat;
DatabaseReference mDatabaseChatDB;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

    matchId = getIntent().getExtras().getString("matchid");
    currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();

    mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("User").child(currentUserID).child("connections").child("matches").child(matchId).child("ChatId");
    mDatabaseChatDB = FirebaseDatabase.getInstance().getReference().child("Chat");

    getChatID();

    mSend = (Button) findViewById(R.id.send);
    mSendEditText = (EditText) findViewById(R.id.message);


    mSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendMessage();
        }

        private void sendMessage() {
            String sendMessageText = mSendEditText.getText().toString();
            if (!sendMessageText.isEmpty()){
                DatabaseReference newMessageDb = mDatabaseChatDB.push();

                Map newMessage = new HashMap<>();
                newMessage.put("createdByUser",currentUserID);
                newMessage.put("text", sendMessageText);

                newMessageDb.setValue(newMessage);
            }
            mSendEditText.setText(null);
        }
    });

    mRecyclerView = (RecyclerView) findViewById(R.id.chatview);
    mRecyclerView.setNestedScrollingEnabled(false);
    mRecyclerView.setHasFixedSize(false);
    mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
    mRecyclerView.setLayoutManager(mChatLayoutManager);
    mChatAdapter = new ChatAdapter(getDataSetChat(),ChatActivity.this);
    mRecyclerView.setAdapter(mChatAdapter);

}

private void getChatID(){
    mDatabaseChat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                chatId = dataSnapshot.getValue().toString();
                mDatabaseChatDB = mDatabaseChatDB.child(chatId);
                getChatMessages();
            }
        }

        private void getChatMessages() {
            mDatabaseChatDB.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                    if (dataSnapshot.exists()){
                        String message = null;
                        String currentuser = null;

                        if (dataSnapshot.child("text").getValue() != null ){
                            message = dataSnapshot.child("text").getValue().toString();
                        }

                        if (dataSnapshot.child("createdByUser").getValue() != null ){
                            currentuser = dataSnapshot.child("createdByUser").getValue().toString();
                        }
                        if(message!= null && currentuser !=null){
                            Boolean currentUserBoolean = false;
                            if(currentuser.equals(currentUserID)){
                                currentUserBoolean = true;
                            }
                            ChatObject newMessage = new ChatObject(message,currentUserBoolean);
                            resultsChat.add(newMessage);
                            mChatAdapter.notifyDataSetChanged();
                        }
                    }
                }

                @Override
                public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
private ArrayList<ChatObject> resultsChat = new ArrayList<ChatObject>();
private List<ChatObject> getDataSetChat() {
    return resultsChat;
}

}

你好@Asif Bin Zahit 将最近的消息放在最上面你必须对代码进行一些更改,如下面的

在数组列表中添加最新消息后resultsChat.add(newMessage) 您必须按降序对数组列表进行排序,然后在调用 notifyDataSetChanged

如果在设置适配器之前列表中已有记录,则必须按如下所述对列表进行排序,然后将适配器设置为回收器视图

Collections.sort(getDataSetChat())
mChatAdapter = new ChatAdapter(getDataSetChat(),ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);

向列表添加新消息时

resultsChat.add(newMessage);
Collections.sort(resultsChat);
mChatAdapter.notifyDataSetChanged();

它会始终将您的最新消息添加到 recyclerview 列表的顶部