0

我正在尝试使用计时器和 sheduleAtFixedRate 方法在 Android 上制作计时器,但看起来在计时器的 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);
        }
    });
}
4

3 回答 3

0

在runnable中操作界面控制。

参考代码:

private Handler handler = new Handler( );

private Runnable runnable = new Runnable( ) {
 public void run ( )
 {
 atextview.setText(String.valueOf(a));
 handler.postDelayed(this,1000); //if continue Timer,use this sentence.
 }
 };
 handler.postDelayed(runnable,1000); // begin Timer
 handler.removeCallbacks(runnable); //stop Timer 
于 2012-11-23T06:11:46.523 回答
0

所有更改或触摸 UI 对象的操作都应在 Thread 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);
        }
    });
}
于 2012-11-22T21:23:37.750 回答
0

您正在尝试在 ui 线程之外更新用户界面。

替换texto_cronometro.setText(String.valueOf(a));为:

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

    public void run() {
        texto_cronometro.setText(String.valueOf(a));
    }
});
于 2012-11-22T21:24:09.730 回答