Android進階之路 - 簡單實現聊天功能

記得幾年以前看到聊天功能時總是不得所以,現在回頭一看,發現其實實現方式非常簡單,故此記錄一番 ~

實現效果

一個入門級的Demo、只能滿足基本需求,用於開闊自身思路 ~

在這裏插入圖片描述

實現思想

  • 一個垂直的list列表
  • 一個有tag的model
  • 通過tag區分用戶、展示不同UI

實現方式

導入依賴

篇中用到的 RecyclerView、 BaseQuickAdapter 均需導入對應依賴 ~

build(Project)

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

build(app)

implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.35'
implementation 'com.android.support:recyclerview-v7:28.+'
創建model

思想: 一個有tag的model

TalkBean

package nkwl.com.chatdemo;

/**
 * @author MrLiu
 * @date 2019/12/23
 * desc
 */
public class TalkBean {
    private int tag;
    private String data;

    public TalkBean(int tag, String data) {
        this.tag = tag;
        this.data = data;
    }

    public int getTag() {
        return tag;
    }

    public void setTag(int tag) {
        this.tag = tag;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
創建適配器

思想:通過tag區分用戶、展示不同UI

CustomAdapter

package nkwl.com.chatdemo;

import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

/**
 * @author MrLiu
 * @date 2019/12/17
 * desc
 */
public class CustomAdapter extends BaseQuickAdapter<TalkBean, BaseViewHolder> {

    private List listData;

    public CustomAdapter(int layoutResId, @Nullable List data) {
        super(layoutResId, data);
        this.listData = data;
    }

    @Override
    protected void convert(BaseViewHolder helper, TalkBean item) {
        TextView left = helper.getView(R.id.tv_left);
        TextView right = helper.getView(R.id.tv_right);

        if (item.getTag() == 1) {
            left.setText("用戶1:" + item.getData());
            left.setVisibility(View.VISIBLE);
            right.setVisibility(View.GONE);
        } else {
            right.setText("用戶2:" + item.getData());
            right.setVisibility(View.VISIBLE);
            left.setVisibility(View.GONE);
        }
    }
}

item_layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv_left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:padding="5dp"
        tools:text="左側" />

    <TextView
        android:id="@+id/tv_right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:padding="5dp"
        tools:text="右側" />
</RelativeLayout>
使用場景

思想:一個垂直的list列表

MainActivity

package nkwl.com.chatdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRv;
    private TextView mSend1;
    private EditText mInput1;
    private TextView mSend2;
    private EditText mInput2;
    private List dataList;
    private CustomAdapter adapter;

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

        initViewAndData();
        onSendClick();
    }

    private void initViewAndData() {
        //找id
        mRv = findViewById(R.id.rv);
        mInput1 = findViewById(R.id.et_input1);
        mSend1 = findViewById(R.id.tv_send1);
        mInput2 = findViewById(R.id.et_input2);
        mSend2 = findViewById(R.id.tv_send2);

        //填數據
        dataList = new ArrayList<TalkBean>();
        dataList.add(new TalkBean(1, "Hi"));
        dataList.add(new TalkBean(2, "Hello"));
        dataList.add(new TalkBean(1, "Let's study together."));
        dataList.add(new TalkBean(2, "ok ~"));

        //去適配
        adapter = new CustomAdapter(R.layout.item_layout, dataList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRv.setLayoutManager(layoutManager);
        mRv.setAdapter(adapter);
    }

    //用戶1、用戶2的輸入事件
    private void onSendClick() {
        mSend1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String putData1 = mInput1.getText().toString().trim();
                Toast.makeText(MainActivity.this, "用戶1:" + putData1, Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(putData1)) {
                    dataList.add(new TalkBean(1, putData1));
                    adapter.notifyDataSetChanged();
                    mInput1.setText("");
                }
            }
        });

        mSend2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String putData2 = mInput2.getText().toString().trim();
                Toast.makeText(MainActivity.this, "用戶2:" + putData2, Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(putData2)) {
                    dataList.add(new TalkBean(2, putData2));
                    adapter.notifyDataSetChanged();
                    mInput2.setText("");
                }
            }
        });
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#C7EDCC"
        android:paddingTop="25dp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:background="#FFDEAD">

        <EditText
            android:id="@+id/et_input1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@null"
            android:hint="請輸入聊天內容"
            android:padding="5dp"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/tv_send1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:background="#f64"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="用戶1:發送"
            android:textColor="#fff"
            android:textSize="12sp" />
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:background="#C7EDCC" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:background="#FFDEAD">

        <EditText
            android:id="@+id/et_input2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@null"
            android:hint="請輸入聊天內容"
            android:padding="5dp"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/tv_send2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:background="#f64"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="用戶2:發送"
            android:textSize="12sp" />
    </RelativeLayout>
</LinearLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章