通过Handler改变TextView的值 package com.example.androidthreadtest;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListen
package com.example.androidthreadtest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * 作者: andli * 时间: 2017/11/1 18:17 * 描述: 通过Handler改变TextView的值 */ public class MainActivity extends Activity implements OnClickListener { private TextView text; private Button changeText; public static final int UPDATE_TEXT = 1; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 处理消息 case UPDATE_TEXT: text.setText("Handler异步操作"); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView) findViewById(R.id.text); changeText = (Button) findViewById(R.id.change_text); changeText.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.change_text: // 子线程 new Thread(new Runnable() { @Override public void run() { Message message = new Message(); message.what = UPDATE_TEXT; handler.sendMessage(message); // 发送消息 } }).start(); break; default: break; } } }