繁体   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