I'm developing a chat UI. When I send a message, it inflates correctly. However, when I send another message, the new message is added at the top of a new screen, instead of below the previous message. In addition, when I receive a reply, it added below the one I sent. After this, the next message received or sent will be added on a new screen. How do I stop this from happening?
Here's my layout.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/message_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/textbox"
/>
<LinearLayout
android:id="@+id/textbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="@+id/txtMessage"
android:hint="Enter message"
android:background="@android:color/transparent"
android:layout_gravity="center"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:maxLines="6"/>
<Button
android:id="@+id/btnSend"
android:text="SEND"
android:textSize="14dp"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:layout_width="64dp"
android:layout_height="48dp"
android:gravity="center"
android:layout_gravity="bottom" />
</LinearLayout>
</RelativeLayout>
Adding a new message to the adapter:
String messageString = txtMessage.getText().toString();
if (messageString.trim().length() > 0) {
// update the views
txtMessage.setText("");
Message message = new Message(messageString);
message.setDirection(Message.OUTGOING_MESSAGE);
adapter.addMessage(message);
The Chat adapter class:
class ChatAdapter
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private final List<Message> messages;
ChatAdapter(Context context, List<Message> messages) {
this.context = context;
this.messages = messages;
}
public void addMessage(Message message) {
messages.add(message);
Log.i("MESSAGE", message.getText());
adapter.notifyDataSetChanged();
}