-1

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

公共类 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();



}
4

2 回答 2

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

    }

}
于 2013-09-20T13:00:50.593 回答
1

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

于 2013-09-20T12:53:54.760 回答