本程序的目的是通过Message+多线程技术实现TextView内容的更新,属于入门级,代码如下。
注意事项:
1、Thread.sleep()的时间太短的话,会导致程序崩溃。
2、在handler里面不能使用Toast.makeTest()方法。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
TestMessage.java
package com.android.message;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;
public class TestMessage extends Activity {
/** Called when the activity is first created. */
private TextView textview;
private int i = 0;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case 255:
textview.setText("i= " + i);
break;
case 256:
textview.setText("finish");
break;
default:
super.handleMessage(msg);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textview1);
textview.setText("hello xiehao!");
new Thread(){
@Override
public void run() {
Message msg = new Message();
try {
for(;i < 10; i++){
msg.what = 255;
handler.sendMessage(msg);
Thread.sleep(3000);
}
msg.what = 256;
handler.sendMessage(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}