看了《第二行代码》一段时间了,这次按照书上的内容,写个聊天界面。
先新建一个空项目day05_UIBestPractice
一、制作Nine-Patch图片
准备一张message
图片,在AS中右击并选择Create 9-Patch file
,保存时命名为message_left.9.png
拖动黑线选择拉伸区域【上左黑边】和放置内容区域【下右】:
原来的message.png
可以删除了,然后修改主布局查看拉伸效果:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/message_left">
</LinearLayout>
运行:
类似的,再做一张message_right.9.png
二、编写聊天界面
1、添加依赖库
implementation 'androidx.recyclerview:recyclerview:1.0.0'
2、编写主界面
RecyclerView
用于显示聊天内容,EditView
输入聊天消息,Button
发送按钮
<?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="#d8e0e8">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/msg_recycler_view"
android:layout_weight="1"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="输入消息"
android:maxLines="2"
android:id="@+id/input_text"
/>
<Button
android:id="@+id/send"
android:layout_width