csh_34 2012-11-23 03:17 采纳率: 0%
浏览 2558
已采纳

在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条回答

  • 问答小助手 2012-12-06 03: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);
            }
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划