简体   繁体   中英

Timer in Android Studio using Runnable

I'm trying to do a timer, but it is just don't work and i can't figure out what should i change to make it work. Can you help me guys?

private TextView timer;
private boolean run = true;
private Integer a = 0;

. . .

public void Start(View view) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
          try {

                    Integer count = a;
                    String sec = count.toString();
                    timer = findViewById(R.id.textView);
                    timer.setText(sec);
                    Thread.sleep(1000);

            } catch (Exception e) {
              timer.setText("Какая-то ошибка");

            } if (run) {
              a++;
            }

       }
    }
    );
    t.start();
}

Try to use a Handler instead of a Thread .

public void Start(View view) {
     final Handler handler = new Handler();
     Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Integer count = a;
            String sec = count.toString();
            timer = findViewById(R.id.textView);
            timer.setText(sec);

            if (run) {
                a++;
            }

            handler.postDelayed(this, 1000);
        }
    };


    handler.postDelayed(runnable, 1000);
}

If you want to implement a countdown and show it in text view. You can simply use android.os.CountDownTimer class instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM