2 csh 34 csh_34 于 2012.11.23 11:17 提问

在Android中制作一个chronometer计时器

我想在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);
        }
    });
}

3个回答

CSDN_Ask
CSDN_Ask   2012.12.06 11:07
已采纳

所有要改变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);
        }
    });
}
lgxing
lgxing   2012.11.23 13:27

要操作界面控件,必须在runnable中,你可以查一下
参考代码:

private Handler handler = new Handler( );

private Runnable runnable = new Runnable( ) {
public void run ( )
{
atextview.setText(String.valueOf(a));
handler.postDelayed(this,1000); //继续Timer,如果不继续,这句就不要
}
};
handler.postDelayed(runnable,1000); // 开始Timer
handler.removeCallbacks(runnable); //停止Timer 
nana4ever
nana4ever   2012.11.23 14:19

更新UI线程之外的用户界面。
用这些代码:

<youractivityname>.this.runOnUiThread(new Runnable() {

    public void run() {
        texto_cronometro.setText(String.valueOf(a));
    }
});

代替

texto_cronometro.setText(String.valueOf(a));
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!