开发者社区 问答 正文

怎样制作一个chronometer计时器

我想在Android中制作一个chronometer计时器,使用了timer和sheduleAtFixedRate 方法。看起来像是在timer的run方法中调用textview后,程序就会出错停止运行。我用的是以下的代码,哪里出错了呢?
screenshot

展开
收起
蛮大人123 2016-02-15 10:47:40 2057 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    所有要改变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);
            }
        });
    }
    2019-07-17 18:43:02
    赞同 展开评论
问答分类:
问答地址: