各位大大好,想请教一个关于handler的问题,
我想额外开一个Thread在背景数10秒,
并且在每一秒的时候在MainThread分别显示1,2,3...,10
但是会跳出错误讯息如下:
Only the original thread that created a view hierarchy can touch its views.
我已经开了CountThread2在里面计算数值,并且利用Bundle,Message绑住讯息,
再用Handler传到MainThread显示数值,我看不出来问题点在哪@@
请问我的程式码哪里出了问题?
public class MainActivity extends ActionBarActivity {
private TextView txt_show;
private Button btn_start;
CountThread2 countThread2 = new CountThread2();
android.os.Handler handler = new android.os.Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
txt_show.setText(Integer.toString(msg.getData().getInt("count",
0)));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_show = (TextView)findViewById(R.id.txt_show);
btn_start = (Button)findViewById(R.id.btn_start);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
countThread2.start();
}
});
}
class CountThread2 extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
Bundle bundle = new Bundle();
bundle.putInt("count", i + 1);
Message message = new Message();
message.setData(bundle);
handler.handleMessage(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}