Home > Software engineering >  Simple Countdown in Android Studio using JAVA
Simple Countdown in Android Studio using JAVA

Time:09-21

I'm trying to make simple 60seconds countdown timer in Android Studio using java. Only problem is that it appears like this: "00:60". But I want it to be like this: "60". And also I want to reset and switch to another class as soon as timer hits 0. And when I visit this timer activity I want it to start timer again and so on... Here's my java code:

public class BeginAfter extends AppCompatActivity {

    TextView textView;

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

        textView = findViewById(R.id.timer);

        long duration = TimeUnit.MINUTES.toMillis(1);

        new CountDownTimer(duration, 1000){
            @Override
            public void onTick(long l) {
                String sDuration = String.format(Locale.ENGLISH,"d : d"
                    ,TimeUnit.MILLISECONDS.toMinutes(l)
                    ,TimeUnit.MILLISECONDS.toSeconds(l) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l)));

                textView.setText(sDuration);
            }

            @Override
            public void onFinish() {
                textView.setVisibility(View.INVISIBLE);
            }
        }.start();
    }
}

And here's my xml code:

<TextView
        android:id="@ id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#d10e00"
        android:textSize="37dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.064" />

CodePudding user response:

Try:

String sDuration = 
       String.format(
              Locale.ENGLISH,
              "d",
              TimeUnit.MILLISECONDS.toSeconds(l) -
              TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l))
       );

This will replace d in the String "d" with the first given integer in the following arguments of String.format and try to display it with only 2 digits.

  • Related