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



嗨,我正在尝试每秒更新 3 个文本视图。我写了这段代码。线程正常启动,但文本视图它们不会更新。我在文本视图的文本参数中传递一个函数,该函数以数字形式获取当前系统时间(使用日历),然后将其转换为字母。示例:对于 3.45 三四十五。任何帮助将不胜感激。谢谢

公共类 主活动扩展活动 {

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();

}

试试这个,

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());
            }
        });
    }
}
为此

使用计时器,我认为是因为线程无法更新您的 UI。

最新更新