我想在Android中制作一個chronometer計時器,使用了timer和sheduleAtFixedRate 方法。看起來像是在timer的run方法中調用textview後,程序就會出錯停止運行。我用的是以下的代碼,哪裡出錯了呢?
Button boton_iniciar;
TextView texto_cronometro;
Timer count;
int a = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cronometro);
/**********************/
boton_iniciar = (Button) findViewById(R.id.button1);
texto_cronometro = (TextView) findViewById(R.id.textView1);
count= new Timer("Contador");
boton_iniciar.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
count.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
a++;
texto_cronometro.setText(String.valueOf(a));
}
}, 100, 100);
}
});
}
所有要改變UI對象的的action都應該在主UI中運行。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cronometro);
/**********************/
boton_iniciar = (Button) findViewById(R.id.button1);
texto_cronometro = (TextView) findViewById(R.id.textView1);
count= new Timer("Contador");
boton_iniciar.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
count.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
a++;
ActivityCronometro.this.runOnUiThread(new Runnable() {
@Override
public void run() {
texto_cronometro.setText(String.valueOf(a));
}
});
}
}, 100, 100);
}
});
}