Android实现聊天界面
作者:Thierryxc 发布时间:2023-04-09 22:57:57
本文实例为大家分享了Android实现聊天界面的具体代码,供大家参考,具体内容如下
文件目录
在app下的build.gradle中添加依赖库(RecyclerView)
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.uibestpractice"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguarrules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:recyclerview-v7:24.2.1'//添加RecyclerView依赖库
testCompile 'junit:junit:4.12'
}
编写主界面(activity_main.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:background="#d8e0d8">
<android.support.v7.widget.RecyclerView
android:id="@+id/msg_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/input_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type something here"
android:maxLines="2"/>
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"/>
</LinearLayout>
</LinearLayout>
在主界面中放置的RecyclerView用于显示消息
EditText用于编辑消息
Button用于发送消息
定义消息的实体类Msg
package com.example.uibestpractice;
public class Msg {
public static final int TYPE_RECEIVED = 0;
public static final int TYPE_SENT = 1;
private String content;
private int type;
public Msg(String content,int type) {
this.content = content;
this.type = type;
}
public String getContent() {
return content;
}
public int getType() {
return type;
}
}
用两个常量来表示消息的类型(接收的还是发送的)
编写RecyclerView的子布局(msg_item.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="wrap_content"
android:padding="10dp">
<LinearLayout
android:id="@+id/left_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="@drawable/message_left">
<TextView
android:id="@+id/left_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textColor="#fff"/>
</LinearLayout>
<LinearLayout
android:id="@+id/right_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="@drawable/message_right">
<TextView
android:id="@+id/right_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"/>
</LinearLayout>
</LinearLayout>
将接收的消息居左对齐,发送的消息居右对齐
创建RecyclerView适配器类
package com.example.uibestpractice;
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 java.util.List;
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder>{
private List<Msg> mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rihgtMsg;
public ViewHolder(View view) {
super(view);
leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
leftMsg = (TextView) view.findViewById(R.id.left_msg);
rihgtMsg = (TextView) view.findViewById(R.id.right_msg);
}
}
public MsgAdapter(List<Msg> msgList) {
mMsgList = msgList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Msg msg = mMsgList.get(position);
if (msg.getType() == Msg.TYPE_RECEIVED) {
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
} else if (msg.getType() == Msg.TYPE_SENT) {
holder.rightLayout.setVisibility(View.VISIBLE);
holder.leftLayout.setVisibility(View.GONE);
holder.rihgtMsg.setText(msg.getContent());
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
}
定义了一个内部类ViewHolder,继承自RecyclerView.ViewHolder。ViewHolder的构造函数中传入一个View参数,这个参数通常是RecyclerView子项的最外层布局,这样我们就可以通过findViewById()方法来获取布局中的接收和发送消息布局的实例了。
MsgAdapter中也有一个构造函数,将要展示的数据源传进来复制给mMsgList。
MsgAdapter继承自RecyclerView.Adapter,必须重写onCreateViewHolder()、onBindViewHolder()、getItemCount()三个方法。
onCreateViewHolder()用于创建ViewHolder实例,在这个方法中将msg_item布局加载进来,然后创建一个ViewHolder实例,并把加载出来的布局传到构造函数中,返回实例。
onBindViewHolder()用于对RecyclerView子项的数据进行赋值。
getItemCount()获得RecyclerView有多少个子项
使用RecyclerView(修改MainActivity)
package com.example.uibestpractice;
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 java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Msg> msgList = new ArrayList<>();
private EditText inputText;
private Button send;
private RecyclerView msgRecyclerView;
private MsgAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMsgs();
inputText = (EditText) findViewById(R.id.input_text);
send = (Button) findViewById(R.id.send);
msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
msgRecyclerView.setLayoutManager(layoutManager);
adapter = new MsgAdapter(msgList);
msgRecyclerView.setAdapter(adapter);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = inputText.getText().toString();
if (!"".equals(content)) {
Msg msg = new Msg(content,Msg.TYPE_SENT);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size()-1);
msgRecyclerView.scrollToPosition(msgList.size()-1);
inputText.setText("");
}
}
});
}
private void initMsgs() {
Msg msg1 = new Msg("Hello",Msg.TYPE_RECEIVED);
msgList.add(msg1);
Msg msg2 = new Msg("I'm John",Msg.TYPE_RECEIVED);
msgList.add(msg2);
Msg msg3 = new Msg("Hello",Msg.TYPE_SENT);
msgList.add(msg3);
}
}
onCreate()方法中先获得了RecyclerView的实例,然后创建了LinearLayoutManager对象,并把它设置到RecyclerView的实例中去。LayoutManager用于指定RecyclerView的布局方式,这里使用是线性布局的意思,可以实现ListView相同的效果。
设置了send按钮的响应事件,如果内容不为空则创建出一个新的Msg对象,并添加到msgList中去,之后调用了适配器的方法notifyItemInserted()来通知列表有新数据插入,这样新增的消息才能在RecyclerView中显示。接着调用RecyclerView的scrollToPosition()方法,将显示的数据定位到最后一行,最后清空输入栏。
效果图:
来源:https://blog.csdn.net/thierryxc/article/details/77715519


猜你喜欢
- 概述从今天开始, 小白我将带大家开启 Java 数据结构 & 算法的新篇章.冒泡排序冒泡排序 (Bubble Sort) 是一种简单
- 配置注解的支持:在spring4之后,想要使用注解形式,必须得要引入 aop 的包<dependency><groupId
- 要“监听”事件,我们总是可以将“ * ”作为事件源中的另一个方法写入事件,但这将使事件源与 * 的逻辑紧密耦合。对于实际事件,我们比直接方法
- 使用Unity API PlayerBuildInterface.CompilePlayerScripts 将项目中的代码生成为 DLL 程
- 压缩包制作也是很多项目中需要用到的功能。比如有大量的文件(假设有10000个)需要上传,1个1个的上传似乎不太靠谱(靠,那得传到什么时候啊?
- 上篇博客我们了解了请求参数的获取,那么获取到请求参数之后,需要对参数进行出来,然后进行数据响应。那么这篇博客我们就来了解 Controlle
- 本文实例讲述了在.net应用程序中运行其它EXE文件的方法。分享给大家供大家参考。具体实现方法如下:Process proc = new P
- 前言Android模拟用户点击。在自动化测试中可使用的工具。可以利用adb命令,也可以使用Android SDK中的monkeyrunner
- 1. java 执行shelljava 通过 Runtime.getRuntime().exec() 方法执行 shell 的命令或 脚本,
- 构造方法以及参数:PageView可用于Widget的整屏滑动切换,如当代常用的短视频APP中的上下滑动切换的功能,也可用于横向页面的切换,
- 目录1、设Tree为已定义的类名,下列语句能正确创建 Tree 对象的是 。2、区分类中重载方法的依据是( )。3、以下代码执行后输出结果为
- App 启动方式冷启动App 没有启动过或 App 进程被杀,系统中不存在该 App 进程,此时启动即为冷启动。需要创建 App 进程,加载
- Task执行任务,等待任务完成代码://任务Func<int> Funcs = () =>{? ? Console.Wri
- Condition是在Spring 4.0 增加的条件判断功能,通过这个可以功能可以实现选择性的创建 Bean操作。思考:SpringBoo
- 进程之间的通信是为了解决不同进程之间的数据传输问题,这样可以让不同程序交互数据。实现进程通信的方式:1、剪切板;2、COM;3、内存映射文件
- <profiles> <profile> <
- 初看 cgaolei 翻译的 Java技巧之双括弧初始化 一文,走马观花,只知用法,未细看后面的解释。蔚为惊艳,心里想 Java 竟然有这么
- 本文实例讲述了C#类中static变量用法。分享给大家供大家参考。具体分析如下:先来看一段代码:using System; namespac
- 1 前言单例模式是我们经常使用的一种模式,一般来说很多资料都建议我们写成如下的模式:/** * Created by qiyei2015 o
- 前言:封装、继承和多态是面向对象编程的三大特征。1.封装1.1.封装概念封装就是把抽象出的数据(属性)和对数据的操作(方法)封装在一起,数据