Chronometer with H:MM:SS

后端 未结 3 1314
陌清茗
陌清茗 2021-01-12 16:15

How to display Chronometer with H:MM:SS? I read MM:SS and H:MM:SS are displaying by default.I found only for MM:SS.

Here is my code for MM:SS with start and stop but

3条回答
  •  星月不相逢
    2021-01-12 17:02

    Chronometer with H:MM:SS

    Divide the time into minute , hour and second using setOnChronometerTickListener.

    use this ......

    Chronometer chrono  = (Chronometer) findViewById(R.id.chronomete);
    chrono.setOnChronometerTickListener(new OnChronometerTickListener(){
            @Override
                public void onChronometerTick(Chronometer chronometer) {
                long time = SystemClock.elapsedRealtime() - chronometer.getBase();
                int h   = (int)(time /3600000);
                int m = (int)(time - h*3600000)/60000;
                int s= (int)(time - h*3600000- m*60000)/1000 ;
                String t = (h < 10 ? "0"+h: h)+":"+(m < 10 ? "0"+m: m)+":"+ (s < 10 ? "0"+s: s);
                chronometer.setText(t);
            }
        });
        chrono.setBase(SystemClock.elapsedRealtime());
        chrono.setText("00:00:00");
    

    EDIT

    For Start

    Declare globally a long variable timeWhenStopped . It is maintain the time .

    private long timeWhenStopped = 0;
    

    Start Listener... get the timeWhenStopped and start from there.

     start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
                chrono.start();
            }
        }); 
    

    Stop Listener.... store the time in timeWhenStopped and stop.

    stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
                chrono.stop();
    
            }
        });
    

    enjoy coding............

提交回复
热议问题