《Android Studio开发实战》学习(二)- 聊天室
背景
在前一篇文章 1中实现了使用Android Studio开发Hello World App 2,在这里继续研究Android Studio的使用方法,熟悉简单控件TextView的使用。本文的目标是开发一个简单的聊天室App,实现点击聊天室窗口添加一条聊天记录,长按聊天窗口可以清除所有聊天记录的功能。
聊天室布局文件的编写
一个简单的聊天室布局如下:
- 标题,居中显示一行文字“聊天室效果,点击添加聊天记录,长按删除聊天记录”,高度为10%,宽度为整个屏幕;
- 聊天记录窗口,高度为90%,宽度为整个屏幕,点击在聊天记录窗口添加一句随机文本,并附上时间戳,长按清除文本。
为了实现百分比布局,可以在ConstraintLayout中采用添加辅助线(Guideline)的方法 3。在这个聊天室中,可以在0.10的位置添加一条水平辅助线,这样标题、聊天窗口的比例就是10%,90%。然后把2个textview的layout_width和layout_height都设置为0,用辅助线来限制 4。
activity_main.xml
的完整代码如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline_1"
app:layout_constraintGuide_percent=".10"
android:orientation="horizontal"/>
<TextView
android:id="@+id/tv_control"
android:layout_width="0dp"
android:layout_height