在android开发中,如果在一个线程中想更新主界面中控件显示的数据,直接给主界面控件赋值就会出现异常,android中为了安全起见,是不允许在线程中更新界面控件的数据,遇到这种情况,我们可以使用Handler. Handler就是处理界面和线程间的消息传递,通信的组件。下面我们演示下handler处理详细的两种办法,下面的这个列子通过点击不同按钮展现handler.post和handler.sendmsg两个传递消息的方法。
1. Handler.Post
创建一个handler对象和Runnable对象,通过handler.post(new Runnable(){});处理来更新界面中的textview的数据
2.Handler.sendMessage
这个例子中,我们创建一个employee员工类,单击按钮的时候,显示员工的信息,通过handler.sendmessage来传递消息和参数进行处理
全部代码
<?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" >
<TextView
android:id="@+id/textViewMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="@+id/btnpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="handler post" />
<Button
android:id="@+id/btnmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="handler message" />
</LinearLayout>
package com.example.helloword;
import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class HandlerActivity extends Activity {
private TextView tv;
private Button btnpost;
private Button btnmsg;
private Handler handler=new Handler();//post处理handler
//sendmsg处理handler
private Handler handlerTwo=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
tv.setText("姓名:"+((employee)msg.obj).name);
break;
}
}
};
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.handlerlayout);
tv=(TextView)findViewById(R.id.textViewMsg);
btnpost=(Button)findViewById(R.id.btnpost);
btnmsg=(Button)findViewById(R.id.btnmsg);
btnpost.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread=new Thread(new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
handler.post(runOne);
}
}
);
thread.start();
}
});
btnmsg.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread=new Thread(new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
Message msg=new Message();
msg.arg1=1;
employee employeeone=new employee();
employeeone.name="员工1";
employeeone.age=20;
msg.obj=employeeone;
msg.what=0;
handlerTwo.sendMessage(msg);
}
}
);
thread.start();
}
});
}
Runnable runOne=new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
tv.setText("正在执行handler post");
}
};
public class employee
{
public String name;
public int age;
}
}