异步消息处理机制

来源:互联网 发布:淘宝达人 插件 编辑:程序博客网 时间:2024/04/28 14:40

使用一个消息处理机制,开辟一个子线程,通过使用Handler Message Looper 实现更新TextView 的动作

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:id="@+id/change_text"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Change Text"/>    <TextView        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="Hello World"        android:textSize="20sp"/></RelativeLayout>

import android.os.Handler;import android.os.Message;import android.support.v4.widget.TextViewCompat;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 {    public static final int UPDATE_TEXT = 1;//更新TextView    private TextView text;    private Handler handler = new Handler() {//消息处理机制        public void handleMessage(Message msg) {            switch (msg.what) {                case UPDATE_TEXT:                    // 在这里可以进行UI操作                    text.setText("Nice to meet you");                    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_text);        changeText.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch(view.getId()){            case R.id.change_text:                new Thread(new Runnable() {//开辟一个子线程                @Override                public void run() {                    Message message = new Message();//创建Message对象                    message.what = UPDATE_TEXT;//用于发送和处理消息                    handler.sendMessage(message);//消息发送                }            }).start();                break;        }    }}




0 0