<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("匿名内部类方法");
}
}
}
}
android studio 55[2]线程更新UI handler 2
最新推荐文章于 2024-08-30 08:39:36 发布