如何从使用runnable接口的类更新UI上的TextView?

时间:2017-06-05 16:41:00

标签: java android

public class Stopper implements  Runnable {

     private  long mStartTime;
     private volatile int since;
     private Handler handler;
     private TextView tv;
     private Activity activity;
     private Context context;


    /*
    * Constants
    * */
        public static final int MILISEC_TO_MINUTE = 60000;
        public static final int MILISEC_TO_HOUR = 3600000;

    /*
    * Flags
    * */
        private boolean mIsRunning;

        public Stopper(){
          //this.context = context;
            activity = (Activity)context;
            Message message = Message.obtain();
            handler = new Handler(Looper.getMainLooper());

        }
        public void start(){
            mStartTime = System.currentTimeMillis();
            mIsRunning = true;


        }
        public void stop(){
            mIsRunning = false;
        }

        @Override
        public void run () {
            while (mIsRunning) {
                        since = (int)(System.currentTimeMillis() - mStartTime);
                        int hours =  (since / MILISEC_TO_HOUR) % 24; // ms -> h; 360 000= 1[h]
                        int minutes =  (since / MILISEC_TO_MINUTE) % 60;// ms -> min; 60 000[ms] = 1[min]
                        int seconds =  (since / 1000) % 60; //  ms -> s ;1 000[ms] = 1[s] -> (1000 [ms] /1000)%60 = 1[s]
                        int ms =  since % 1000;


                tv.setText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, ms));


                //((Activity) context).updateTimerText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, ms));
            }
        }
    public void getStooperTextView(TextView textView)
    {
        this.tv = textView;
    }

    public int getSince() {
        return since;
    }
}

我阅读了一些关于chronometer的教程。它工作正常,直到我开始需要在两个不同的活动中使用计时器。下面的代码行需要返回值。

((Activity) context).updateTimerText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, ms));

所以,我尝试使用Handler类,但为了做到这一点,我需要一个可运行的对象。

1 个答案:

答案 0 :(得分:1)

我相信方法Activity#runOnUiThread就是您所需要的