Learning "Android Studio Development Practice" (7) - Message Communication between Activities

Learning "Android Studio Development Practice" (7) - Message Communication between Activities


background

Continue to learn how to use Android Studio 4.1.3 here, write a chat tool 1 , and realize the jump and message communication between two Activities. Now I want to design a chat tool that includes two pages, each page includes an input box EditText, a button Button and a text view TextView, to achieve the first page enter a sentence in the input box, and then click the button to jump Go to the second page, and display the text and sending time in the input box of the first page in the text view of the second page. Enter a sentence of text in the input box on the second page, and then click the button to return to the first page and display the entered text in the text view.

Use Intent to pass messages

Multiple Activity pages can be created in Android Studio, and the message transmission between them is realized through Intent. The setClass() method is used to specify the source class and target class name. The first parameter is the Activity that sends the information, and the second parameter is the Activity that receives the information. The putExtra() method is used to pass parameters. The startActivity() method is used to send request data, and the startActivityForResult() method is used to process the response data of the target page.

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);

On the target page, to receive the data sent by the previous page, use the getExtras() method of the Bundle class.

Bundle bundle = getIntent().getExtras();
String request_time = bundle.getString("request_time");
String request_content = bundle.getString("request_content");

Writing layout files

Layout file for the first pagelayout/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="@+id/btn_request"
        android:layout_width="170dp"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:text="Show"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline_1"
        app:layout_constraintBottom_toBottomOf="@+id/guideline_2" />
    <TextView
        android:id="@+id/tv_request"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="left|top"
        android:scrollbars="vertical"
        android:textSize="18sp"
        android:textColor="@color/black"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline_2"
        app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • Experience: The auxiliary line in ConstraintLayout can be mixed with layout_width and layout_height. For example, the upper and lower sides of the button control are limited by the auxiliary line
        app:layout_constraintTop_toTopOf="@+id/guideline_1"
        app:layout_constraintBottom_toBottomOf="@+id/guideline_2"

The left and right are limited by the layout_width parameter:

        android:layout_width="170dp"

as the picture shows:
Learning "Android Studio Development Practice" (7) - Message Communication between Activities - Page Layout

Layout file for the second pagelayout/activity_response.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=".Response">
    <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_response"
        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="@+id/btn_response"
        android:layout_width="170dp"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:text="Show"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline_1"
        app:layout_constraintBottom_toBottomOf="@+id/guideline_2" />
    <TextView
        android:id="@+id/tv_response"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="left|top"
        android:scrollbars="vertical"
        android:textSize="18sp"
        android:textColor="@color/black"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline_2"
        app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

The placement of the controls is exactly the same as in the first Activity, but the names of the controls are different. Strictly speaking, the names of the controls could also be the same, but that would make no sense2 .

Writing code files

Code file for the first pageMainActivity.java

package com.example.activitycommunication;
import androidx.appcompat.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.widget.*;
import android.os.Bundle;
import android.view.View;
import android.view.View.*;
import android.content.Intent;
import java.util.*;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity {
    
    
    private EditText et_request;
    private Button btn_request;
    private TextView tv_request;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_request = (EditText) findViewById(R.id.et_request);
        tv_request = (TextView) findViewById(R.id.tv_request);
        tv_request.setMovementMethod(new ScrollingMovementMethod());
        btn_request = (Button) findViewById(R.id.btn_request);
        btn_request.setOnClickListener(new ClickTAction());
    }
    private class ClickTAction implements OnClickListener {
    
    
        @Override
        public void onClick(View v) {
    
    
            if (v.getId() == R.id.btn_request) {
    
    
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, Response.class);
                intent.putExtra("request_time", getNowTime());
                intent.putExtra("request_content", et_request.getText().toString());
                startActivityForResult(intent, 0);
            }
        }
    }
    private String getNowTime() {
    
    
        SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
        return s.format(new Date());
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
    
    
            String response_time = data.getStringExtra("response_time");
            String response_content = data.getStringExtra("response_content");
            String desc = String.format("收到返回消息:\n返回时间为:%s\n返回内容为:%s\n", response_time, response_content);
            tv_request.setText(tv_request.getText() + desc);
        }
    }
}

Code file for the second pageResponse.java

package com.example.activitycommunication;
import androidx.appcompat.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Response extends AppCompatActivity {
    
    
    private EditText et_response;
    private TextView tv_response;
    private Button btn_response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_response);
        et_response = (EditText) findViewById(R.id.et_response);
        tv_response = (TextView) findViewById(R.id.tv_response);
        tv_response.setMovementMethod(new ScrollingMovementMethod());
        btn_response = (Button) findViewById(R.id.btn_response);
        Bundle bundle = getIntent().getExtras();
        String request_time = bundle.getString("request_time");
        String request_content = bundle.getString("request_content");
        String desc = String.format("收到请求消息:\n请求时间为:%s\n请求内容为:%s\n", request_time, request_content);
        tv_response.setText(tv_response.getText() + desc);
        btn_response.setOnClickListener(new ClickTAction());
    }
    private class ClickTAction implements View.OnClickListener {
    
    
        @Override
        public void onClick(View v) {
    
    
            if (v.getId() == R.id.btn_response) {
    
    
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("response_time", getNowTime());
                bundle.putString("response_content", et_response.getText().toString());
                intent.putExtras(bundle);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        }
    }
    private String getNowTime() {
    
    
        SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
        return s.format(new Date());
    }
}

operation result

According to the previously explored method [^3] to generate the apk file, and then transfer it to the mobile phone to run, the results are as follows:
"Android Studio Development Actual Combat" learning (7) - message communication between Activities - running results


  1. Ouyang Shen. Android Studio Development Practice. Tsinghua University Press. 2017. ↩︎

  2. Learning "Android Studio Development Practice" (1) - Hello World_Xiatangren's Blog-CSDN Blog_android studio learning program development↩︎

Guess you like

Origin blog.csdn.net/quanet_033/article/details/128278159