androidstringchronometer

Getting the time of a Chronometer in a String?


I want to get the time of the Chronometer into a String (or is a string wrong for this kind of use?).

How does it work?

Chronometer mChronometer;
Button button1;
Button button2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mChronometer = (Chronometer) findViewById(R.id.chronometer);

    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);

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

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mChronometer.stop();
        }
    });
}

Solution

  • get the elapsed time in int,

    int elapsed = (int)(SystemClock.elapsedRealtime()-mChronometer.getBase());
    

    convert it to string and then set the text in textview

    textView.setText(String.valueOf(elapsed));