Android之编写聊天界面实践

本文详细介绍了一种基于RecyclerView的聊天界面设计与实现方法,包括消息实体类定义、自定义适配器、界面布局及交互逻辑。

(前提)制作Nine-Path图片
在我的上一节有详细讲解。
制作Nine-Path图片
效果图

编写精美的聊天界面:

既然是要编写一个聊天界面,那肯定要收到的消息和发出的消息。
我们刚刚制作的pop.9.png可以作为收到消息的背景图,那么毫无疑问你还需要再制作一张pop_right.9.png作为发出的消息的背景图。
图片都提供好了就可以开始编码了。由于待会我们会用到RecyclerView,因此首先需要在app/build.gradle当中添加依赖库,如下所示:

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:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
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="wrap_content"
    android:background="#d8e0e8">
<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 net.nyist.lenovo.message_agetest;
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值