簡體   English   中英

我想在textView中顯示線程的計時器(實時)

[英]I would like to show the timer of a thread in textView (Live)

我在一個線程中有一個計時器,等待大約20秒后再轉到新活動,我要尋找的是顯示時間,無論那段時間內textView減少還是增加。 這是我的代碼:

Thread timer = new Thread() {
        public void run() {
            try {
                sleep(ie);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                Intent i = new Intent(Activity.this, Menu.class);
                if (ie == 20000) {
                    startActivity(i);
                    overridePendingTransition(R.anim.pushin, R.anim.pushout);
                }
            }
        }
    };

    timer.start();

謝謝你的協助

嘗試使用CountDownTimer而不是線程:

            CountDownTimer count = new CountDownTimer(20000, 1000)
            {

                int counter = 20;

                @Override
                public void onTick(long millisUntilFinished)
                {
                    // TODO Auto-generated method stub
                    counter--;
                    textView.setText(String.valueOf(counter));

                }

                @Override
                public void onFinish()
                {

            startActivity(i);
            overridePendingTransition(R.anim.pushin, R.anim.pushout);
                }
            };

            count.start();

Camilo Sacanamboy的答案是正確的。 如果要使用線程執行此操作,則一種解決方案可能是這樣的:

final TextView status; //Get your textView here

    Thread timer = new Thread() {
        public void run() {
            int time = 20000;
            try {
                while(time > 0){
                    time -= 200; //Or whatever you might like

                    final int currentTime = time;
                    getActivity().runOnUiThread(new Runnable() { //Don't update Views on the Main Thread
                        @Override
                        public void run() {
                            status.setText("Time remaining: " + currentTime / 1000 + " seconds");
                        }
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                Intent i = new Intent(Activity.this, Menu.class);
                if (ie == 20000) {
                    startActivity(i);
                    overridePendingTransition(R.anim.pushin, R.anim.pushout);
                }
            }
        }
    };

    timer.start();

暫無
暫無

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

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