[問題] 跨執行緒Handler問題
各位大大好,想請教一個關於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();
}
}
}
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.62.58.30
※ 文章網址: https://www.ptt.cc/bbs/AndroidDev/M.1435550150.A.B2F.html
→
06/29 13:27, , 1F
06/29 13:27, 1F
→
06/29 13:48, , 2F
06/29 13:48, 2F
→
06/29 13:59, , 3F
06/29 13:59, 3F