Android development to write a chat room with RecyclerView layout, and add the click event of RecyclerView

Implement the thought order:

1. First of all, we need to prepare 2 .9 png pictures (one picture is the chat bubble on the left, and one picture is the chat bubble on the right), which can be made with the draw9patch.bat tool, and any picture can be imported into the drawable.

2. You need to write a chat room layout xml. The layout consists of android.support.v7.widget. RecyclerView layout to form a chat information list layout, a text input box as information input, and a send Button as a send key.

3. You need to write a sub-layout of the message to display the message in the RecyclerView layout.

4. Write a data class that saves data for subsequent addition to the List

5. Write an adapter class that needs to be used to form a layout

6. Write data in the class of the activity of the chat room layout


1. First we need to prepare 2 png images of .9




2. A chat room layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/chatroomRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/enter"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="@string/contentHints"
            android:layout_weight="1"
            android:maxLines="2"
            />
        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/send"
            />
    </LinearLayout>


</LinearLayout>

3. A sub-layout of a message

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:background="@drawable/leftoo"
        >
        <TextView
            android:id="@+id/left_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:textColor="@color/colcrWhite"
            android:layout_margin="10dp"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/right_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:background="@drawable/right"
        >
        <TextView
            android:id="@+id/right_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:textColor="@color/colcrWhite"
            android:layout_margin="10dp"/>
        
    </LinearLayout>

</LinearLayout>

4. A class that holds data

package com.example.lenovo.mychatroom.data_processing;

import java.util.Date;

/**
 * Created by lenovo on 2018/5/4.
 */
/*
 The data we need to save in the singleton is:
 1. The content of the message;
 2. Type of message: send or receive;
 3. Message creation time
 */
public class Msg {
    private String content;
    private int type;
    private String time;
    public final static int TYPE_RECEIVED=0;
    public final static int TYPE_SENT=1;
    public Msg(String content,int type){
        this.content =content;
        this.type = type;
        this.time = timeData();
    }

    public String getContent() {
        return content;
    }
    public int getType() {
        return type;
    }

    public String getTime() {
        return time;
    }
    /*
    Write a method to get the time
     */
    public String timeData(){
        Date date = new Date();
        String timeData = String.format("%tH",date)
                +String.format("%tM",date)
                +String.format("%tS",date);
        return timeData;

    }
}

5. An adapter class that needs to be used to form a layout

package com.example.lenovo.mychatroom.data_processing;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lenovo.mychatroom.R;

import java.util.List;

/**
 * Created by lenovo on 2018/5/4.
 */

/*
Adapter class, note that the generic type in the adapter class is not a List collection but a Viewholder cache internal class
 */
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
// Write a global variable of List obtained from outside.
    private List<Msg>  msgList;
    /*
    Inner class that caches child layouts
     */
    static  class ViewHolder extends RecyclerView.ViewHolder{
        View myView;
        LinearLayout left_layout;
        LinearLayout right_layout;
        TextView left_msg;
        TextView right_msg;

        public ViewHolder(View itemView) {
            super(itemView);
            myView = itemView;
            left_layout = (LinearLayout)itemView.findViewById(R.id.left_layout);
            right_layout = (LinearLayout)itemView.findViewById(R.id.right_layout);
            left_msg = (TextView)itemView.findViewById(R.id.left_msg);
            right_msg = (TextView)itemView.findViewById(R.id.right_msg);
        }
    }
    /*
    The constructor that passes in the external list
     */
    public MsgAdapter(List<Msg> msgList){
        this.msgList = msgList;
    }
    /*
    Methods that must be overridden
    Fill the child layout into the parent class layout, add the parent class layout to the inner class of the cache layout, and return the cache layout inner class.
    Write the click event of the RecyclerView layout here
     */
    @Override
    public MsgAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
        final ViewHolder holder = new ViewHolder(view);
        holder.myView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();//Get the current clicked position
                Msg msg = msgList.get(position);//Get the singleton in the List from the click position
                // get the time from the singleton
                Toast.makeText(v.getContext(), "Message time: "+msg.getTime(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    /*
    A method that must be overridden to import layout data into the layout
     */
    @Override
    public void onBindViewHolder(MsgAdapter.ViewHolder holder, int position) {
        Msg msg = msgList.get(position);
        //Determine whether the information is received or sent, and judge the layout to be hidden and the layout to be displayed respectively
        if (msg.getType() == Msg.TYPE_RECEIVED){
            // Judging that the information is received, the layout on the left is displayed, and the layout on the right is hidden
            holder.left_layout.setVisibility(View.VISIBLE);
            holder.right_layout.setVisibility(View.GONE);
            holder.left_msg.setText(msg.getContent());
        }
        if (msg.getType() == Msg.TYPE_SENT){
            holder.right_layout.setVisibility(View.VISIBLE);
            holder.left_layout.setVisibility(View.GONE);
            holder.right_msg.setText(msg.getContent());
        }
    }
// A method that must be overridden to return the length of the list
    @Override
    public int getItemCount() {
        return msgList.size();
    }
}

6. Write data in the class of the activity of the chat room layout

package com.example.lenovo.mychatroom;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.lenovo.mychatroom.data_processing.Msg;
import com.example.lenovo.mychatroom.data_processing.MsgAdapter;

import java.util.ArrayList;
import java.util.List;

public class MyChatroomDemo extends AppCompatActivity {
    private List<Msg> msgList = new ArrayList<>();
    private EditText editText;
    private Button sendButton;
    private RecyclerView recyclerView;
    private MsgAdapter msgAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_my_chatroom_demo);
        initMsgs();
        editText = (EditText)findViewById(R.id.enter);
        sendButton = (Button)findViewById(R.id.send);
        recyclerView =(RecyclerView)findViewById(R.id.chatroomRecyclerView);
        // layout arrangement
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        msgAdapter = new MsgAdapter(msgList);
        recyclerView.setAdapter(msgAdapter);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // get the content of the input box
                String content = editText.getText().toString();
                // judge that the content is not empty
                if(!"".equals(content)){
                    //Add content to the singleton
                    Msg msg = new Msg(content,Msg.TYPE_SENT);
                    msgList.add(msg);
                    // ask the adapter to refresh
                    msgAdapter.notifyItemInserted(msgList.size()-1);
                    //Require the recyclerView layout to refresh the message
                    recyclerView.scrollToPosition(msgList.size()-1);
                    editText.setText("");
                }
            }
        });
    }
    public void  initMsgs(){
        Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("Thank you! Hello.",Msg.TYPE_SENT);
        msgList.add(msg2);
        Msg msg3 = new Msg("加班么?",Msg.TYPE_RECEIVED);
        msgList.add(msg3);


    }

}

Realized renderings:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733581&siteId=291194637