Android异步消息处理机制

安卓子线程无法直接更改UI,所以需要异步消息处理机制来解决

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
> <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_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World"
android:textSize="20sp"/> </LinearLayout>
package com.example.contacttest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class NotificationTest extends Activity implements View.OnClickListener{ private Button changeText;
private TextView textContent; private static final int UPDATE_TEXT = 1; private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE_TEXT:
textContent.setText("Nice to meet you!");
break;
default:
break;
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_test); changeText = (Button)findViewById(R.id.change_text);
textContent = (TextView)findViewById(R.id.text_content); 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;
}
} }
上一篇:java hashCode()与equals()的作用


下一篇:Java hashCode() 和 equals()的若干问题解答<转载自skywang12345>