android studio 55[2]线程更新UI handler 2
16lz
2022-01-22
<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 实现圆形ImageView的方法步骤
- Android(安卓)获取屏幕分辨率
- Android连接网络
- Android(安卓)getWindow().setFlags方法
- Android(安卓)Glide 升级4.8 后, 原方法error/preload/fallback
- Android(安卓)数据存储与读取:文件
- android 2.2+ 完全退出程序的方法
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用