在main.xml中:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#000000">
<TextView
android:id="@+id/info"
android:layout_marginTop="8dp"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:textColor="#ffffff"/>
<Button
android:id="@+id/but"
android:layout_marginTop="16dp"
android:layout_width="60dp"
android:layout_height="40dp"
android:background="#3399ff"
android:textColor="#ffffff"
android:text="启动"/>
</LinearLayout>
在MyMessage.java中:
package com.li.message;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MyMessage extends Activity {
private TextView info = null;
private static final int SET = 1; //操作的what状态
private Button but = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.info = (TextView)super.findViewById(R.id.info);
this.but = (Button)super.findViewById(R.id.but);
this.but.setOnClickListener(new OnClickListenerImpl());
}
private class OnClickListenerImpl implements OnClickListener{
public void onClick(View v) {
Looper looper = Looper.myLooper();
MyHandler myHandler = new MyHandler(looper);
myHandler.removeMessages(0); //情况所有的信息
String data = "李叶文"; //要传递的数据
Message msg = myHandler.obtainMessage(SET,1,1,data); //创建信息
myHandler.sendMessage(msg); //发送信息
}
}
private class MyHandler extends Handler{
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case SET: //更新组件
MyMessage.this.info.setText(msg.obj.toString()); //设置文本组件
}
}
}
}