安卓开发笔记(十九):异步消息处理机制实现更新软件UI

主界面代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"> <Button
android:id="@+id/change"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="改变内容"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="你好,世界!"
android:textSize="20sp"/> </RelativeLayout>

主活动代码:

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView text;
public static final int UPDATE_TEXT=;
private Handler handler=new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case UPDATE_TEXT:
text.setText("遇见你真好");
break;
default:
break; }
} };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView)findViewById(R.id.text);
Button ChangeText=(Button)findViewById(R.id.change);
ChangeText.setOnClickListener(this);
}
public void onClick(View v)
{
switch (v.getId())
{
case R.id.change:
new Thread(new Runnable() {
@Override
public void run() {
Message message=new Message();
message.what=UPDATE_TEXT;
handler.sendMessage(message); }
}).start();
break;
default:
break;
} }
}
上一篇:COJ966 WZJ的数据结构(负三十四)


下一篇:poj2114 树分治(点分治)