《Android Studio开发实战》学习(七)- Activities之间的消息通讯
背景
在这里继续学习Android Studio 4.1.3的使用方法,编写一个聊天工具 1,实现两个Activity之间的跳转和消息通讯。现在想要设计一个包括两个页面的聊天工具,每个页面包括一个输入框EditText、一个按钮Button和一个文本视图TextView,实现第一个页面在输入框中输入一句文字,然后点击按钮,就跳转到第二个页面,并且在第二个页面的文本视图中显示第一个页面输入框中的文字和发送时间。在第二个页面的输入框中输入一句文字,然后点击按钮,就回到第一个页面,并且在文本视图中显示输入的文字。
使用Intent传递消息
在Android Studio中可以建立多个Activity页面,它们之间消息的传递是通过Intent实现的。setClass()方法用于指定来源类与目标类名,第一个参数是发送信息的Activity,第二个参数是收取信息的Activity。putExtra()方法用于传递参数。startActivity()方法用于请求数据的发送,startActivityForResult()方法用于还要处理目标页面应答数据的情况。
Intent intent = new Intent();
intent.setClass(MainActivity.this, ActResponseActivity.class);
intent.putExtra("request_time", getNowTime());
intent.putExtra("request_content", et_request.getText().toString());
startActivityForResult(intent, 0);
在目标页面,要接收前一个页面发送过来的数据,使用Bundle类的getExtras()方法。
Bundle bundle = getIntent().getExtras();
String request_time = bundle.getString("request_time");
String request_content = bundle.getString("request_content");
布局文件的编写
第一个页面的布局文件layout/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=".20"
android:orientation="horizontal"/>
<androidx.constraintlayout.widget.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline_2"
app:layout_constraintGuide_percent=".30"
android:orientation="horizontal"/>
<EditText
android:id="@+id/et_request"
android:layout_width="0dp"
android:layout_height="0dp"
android:inputType="text"
android:singleLine="true"
android:textSize="18sp"
android:textColor="@color/black"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="@+id/guideline_1"/>
<Button
android:id</