Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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,"%02d : %02d"
                    ,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" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...