android studio 55[2]线程更新UI handler 2

本文介绍了一个Android应用程序如何通过使用Handler实现主线程与子线程之间的通信,以更新UI元素。具体展示了如何在子线程中发送消息,并在主线程中接收并处理这些消息以改变TextView的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/mTxtShowTest"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/mBtn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="174dp"
        tools:layout_editor_absoluteY="470dp" />

主代码:
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 MainActivity extends AppCompatActivity {
    TextView mTxtShowTest;
    Button mBtn1, mBtn2, mBtn3;
    // 2、在主线程中创建自定义Handler(mHandler)的实例
    private mHandler mhandler = new mHandler();

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

        mTxtShowTest = (TextView) findViewById(R.id.mTxtShowTest);
        mBtn1 = (Button) findViewById(R.id.mBtn1);

        mBtn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 3、创建所需消息对象
                        Message msg = Message.obtain();
                        msg.what = 1;

                        //4、发送消息
                        mhandler.sendMessage(msg);
                    }
                    // 5、开启线程
                }).start();
            }
        });
    }

    //1、自定义Handler子类,继承Handler,重写handleMessage()方法
    class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //执行的UI操作
            if (msg.what==1){
                mTxtShowTest.setText("匿名内部类方法");
            }
        }
    }
}



在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值