public class MainActivity extends AppCompatActivity {
private static int UPDATE = 200;
private TextView mTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv = (TextView) findViewById(R.id.tv);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == UPDATE) {
// 更新界面上的textview
mTv.setText(String.valueOf(msg.obj));
}
super.handleMessage(msg);
}
};
public void click(View view) {
Toast.makeText(this, "点击了", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(5000);
Message msg = new Message();
msg.what = UPDATE;
msg.obj = "异步更新后的值";
handler.sendMessage(msg);
}
}).start();
}
}
网友评论