簡體   English   中英

如何使用可運行接口從類中更新UI上的TextView?

[英]How to update TextView on UI from the class which using runnable interface?

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

我讀了一些有關天文鍾的教程。 在我開始需要在兩個不同的Activity中使用天文鍾之前,它工作正常。 下面的代碼行要求返回值。

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

因此,我嘗試使用Handler類,但要執行此操作,我需要一個可運行的對象。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM