更新每秒或每分钟显示当前时间的文本视图

时间:2013-09-20 12:50:24

标签: android timer textview runnable auto-update

嗨,我想每秒更新3次textviews。我写了这段代码。线程正常启动但文本视图不会更新。我在文本视图的文本参数中传递一个函数,该函数以数字形式获取当前系统时间(使用Calendar),然后将其转换为字母。例如:3.45 THREE FORTYFIVE。任何帮助,将不胜感激。感谢

公共类MainActivity扩展了Activity {

TextView currentv;
GetDate gd;
TextView currentmin;
TextView currentmins;
private Handler mHandler;
private boolean Running = true;







@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);





    currentv = (TextView) this.findViewById(R.id.tvtimehour);
    currentmin = (TextView) findViewById(R.id.tvtimemin);
    currentmins = (TextView) findViewById(R.id.tvtimesecond);



    gd = new GetDate();



    currentv.setText(gd.calculateTimeHour());
    currentmin.setText(gd.calculateTimeMinute());
    currentmins.setText(gd.calculateTimeMinuteDigit());



    mHandler = new Handler();
    Runnable runb = new Runnable(){

        @Override
        public void run(){
            while(Running == true){

                try{
                Thread.sleep(1000);
                }
                catch(Exception e){

                    e.printStackTrace();

                }

                mHandler.post(new Runnable(){
                    @Override
                    public void run(){


                             currentv.setText(gd.calculateTimeHour());
                     currentmin.setText(gd.calculateTimeMinute());
                                 currentmins.setText(gd.calculateTimeMinuteDigit());

                    }



                });


            }


        }





    };

    new Thread(runb).start();



}

2 个答案:

答案 0 :(得分:2)

试试这个,

private MyTimerTask mytask;
private Timer timer;
mytask = new MyTimerTask();
timer = new Timer();
timer.schedule(mytask, 0,60000);

计时器类:

  class MyTimerTask extends TimerTask {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        runOnUiThread(new Runnable() {
            public void run() {
                // Do your stuff here it will work
                           currentv.setText(gd.calculateTimeHour());
                           currentmin.setText(gd.calculateTimeMinute());
                           currentmins.setText(gd.calculateTimeMinuteDigit());
            }
        });

    }

}

答案 1 :(得分:1)

使用Timer,我认为因为Thread无法更新你的UI。