android child thread uses the handle to modify the contents of main thread

1, using the handle to modify the child thread thread main content simple case

1)、activity_handle.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=".HandleActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="129dp"
        android:layout_marginTop="69dp"
        android:text="@string/显示内容"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="116dp"
        android:layout_marginTop="248dp"
        android:text="@string/button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

2、HandleActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HandleActivity extends AppCompatActivity {
    private Button btn;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handle);

        btn = findViewById(R.id.button3);
        tv = findViewById(R.id.textView);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(){

                    @Override
                    public void run() {
                            super.run();
                        Message msg=new Message();
                        msg.what . 1 = ; 
                        handler.sendMessage (MSG); 
                    } 
                } .start (); 
            } 
        }); 
    } 

    Handler Handler = new new Handler () { 
        @Override 
        public  void the handleMessage (the Message MSG) {
             Super .handleMessage (MSG);
             IF (MSG ==. 1 .what ) { 
                tv.setText ( "child thread using the main thread to modify contents of the control handle" ); 
            } 
        } 
    }; 
}

 

Guess you like

Origin www.cnblogs.com/zoro-zero/p/11407467.html