Android-Message更新UI
运行截图:
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:text="TextView"
android:textSize="25sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="子线程直接更新UI会崩溃" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="主线程通过异步消息更新UI" />
</LinearLayout>
</LinearLayout>
主类:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int UPDATE_TEXT = 1;
private TextView textView;
private Button button1;
private Button button2;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_TEXT:
textView.setText("更新后的TextView");
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
textView = findViewById(R.id.textView);
button1 = findViewById(R.id.btn1);
button2 = findViewById(R.id.btn2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
// 子线程直接更新UI程序会崩溃
new Thread(new Runnable() {
@Override
public void run() {
textView.setText("更新后的TextView");
}
}).start();
break;
case R.id.btn2:
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
break;
}
}
}