android studio 55线程更新UI handler
程序员文章站
2022-03-11 18:55:22
第一步activity-main.xml
第一步activity-main.xml
<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/mBtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="177dp"
tools:layout_editor_absoluteY="595dp" /
第二步 MainActivity.java
package com.example.myhandler2;
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 mBtn;
//1、在主线程中通过匿名内部类创建Handler类对象
private Handler mhandler2 = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//执行的UI操作
if (msg.what==1){
mTxtShowTest.setText("匿名内部类方法");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTxtShowTest = (TextView) findViewById(R.id.mTxtShowTest);
mBtn = (Button) findViewById(R.id.mBtn2);
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
// 2、创建所需消息对象
Message msg = Message.obtain();
msg.what = 1;
//3、发送消息
mhandler2.sendMessage(msg);
}
//4、开启线程
}).start();
}
});
}
}
本文地址:https://blog.csdn.net/weixin_33595571/article/details/107954533
上一篇: Unity工程导出至XCode
下一篇: Android 将布局变成 控件