Android: simple time counter

后端 未结 6 2221
-上瘾入骨i
-上瘾入骨i 2020-12-09 02:56

I have a simple program with one TextView and two Buttons: Button1 and Button2.

Clicking on Button 1 will start a counter, increasing by 1 every 1 second and show res

相关标签:
6条回答
  • 2020-12-09 03:31

    Perfect solution if you want to display running clock.

    private void startClock(){
        Thread t = new Thread() {
    
            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Calendar c = Calendar.getInstance();
    
                                int hours = c.get(Calendar.HOUR_OF_DAY);
                                int minutes = c.get(Calendar.MINUTE);
                                int seconds = c.get(Calendar.SECOND);
    
                                String curTime = String.format("%02d  %02d  %02d", hours, minutes, seconds);
                                clock.setText(curTime); //change clock to your textview
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };
    
        t.start();
    }
    
    0 讨论(0)
  • 2020-12-09 03:31

    This way it is much simpler. It is a feature made available on the android developer site. Link

    public void initCountDownTimer(int time) {
        new CountDownTimer(30000, 1000) {
    
            public void onTick(long millisUntilFinished) {
                textView.setText("seconds remaining: " + millisUntilFinished / 1000);
            }
    
            public void onFinish() {
                textView.setText("done!");
            }
        }.start();
    }
    
    0 讨论(0)
  • 2020-12-09 03:35

    Chekout this example, that uses the Chronometer class: http://android-er.blogspot.com/2010/06/android-chronometer.html

    Using the Chronometer class will save you managing the thread yourself.

    0 讨论(0)
  • 2020-12-09 03:36

    As @hovanessyan suggested: You can use the Chronometer class. E.g., as follows (with Kotlin, Java analog):

    class ChronometerToggler: Fragment() {
        private lateinit var chronometer: Chronometer
        private var isChronometerRunning = false
        private lateinit var toggleButton: FloatingActionButton
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            val view = inflater.inflate(R.layout.my_layout, container, false)
            chronometer = view.findViewById(R.id.chronometer)
            toggleButton = view.findViewById(R.id.toggle_button)
            toggleButton.setOnClickListener {
                onToggleButtonPressed()
            }
            return view
        }
    
        private fun onToggleButtonPressed() {
            isChronometerRunning = !isChronometerRunning
            if (isChronometerRunning) {
                chronometer.base = SystemClock.elapsedRealtime()
                chronometer.start()
            }
            else {
                chronometer.stop()
            }
        }
    }
    
    

    In the my_layout.xml:

    [...]
         <Chronometer android:id="@+id/chronometer" [...]/>
    [...]
    
    0 讨论(0)
  • 2020-12-09 03:46

    You can introduce flag. Something like isPaused. Trigger this flag whenever 'Pause' button pressed. Check flag value in your timer task. Success.

    Timer T=new Timer();
    T.scheduleAtFixedRate(new TimerTask() {         
            @Override
            public void run() {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        myTextView.setText("count="+count);
                        count++;                
                    }
                });
            }
        }, 1000, 1000);
    
    
     onClick(View v)
     {
          //this is 'Pause' button click listener
          T.cancel();
     }
    
    0 讨论(0)
  • 2020-12-09 03:48

    Pavel is on the right track with stopping it, except his answer is a waste since it doesn't stop the Timer. Do this on the part he posted with the added else statement:

    if(!isPaused)
            {
                myTextView.setText("count="+count);
                count++;                
            } else {
                cancel();//adding this makes it actually stop
            }
    

    Oh and you said it crashed. We have no idea why it's crashing, so unfortunately we cannot really help figuring out why its doing that unless we see more code and the error.

    Good catch @yorkw The problem is obviously with something its trying to do when its starts running. Since its says "Timer-0", this means it never starts officially and it gets stuck in that part. First rule of running threads, NEVER CHANGE UI ELEMENTS FROM OUTSIDE THE UI. I would suggest using runOnUiThread like york said. Here's a link on how to use it: runOnUiThread. Pretty sure TimerTask is a runnable meaning it runs on a separate thread. Least thats what I noticed on the docs.

    0 讨论(0)
提交回复
热议问题