使用 JAVA 在 Android Studio 中简单倒计时 [英] Simple Countdown in Android Studio using JAVA

查看:82
本文介绍了使用 JAVA 在 Android Studio 中简单倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 java 在 Android Studio 中制作简单的 60 秒倒数计时器.唯一的问题是它看起来像这样:00:60".但我希望它是这样的:60".而且我想在计时器达到 0 时立即重置并切换到另一个类.当我访问这个计时器活动时,我希望它再次启动计时器等等......这是我的 java 代码:

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();
    }
}

这是我的 xml 代码:

<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" />

推荐答案

尝试:

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

这会将字符串 "%02d" 中的 %02d 替换为 String.format 的以下参数中的第一个给定整数,并尝试仅显示它2 位数.

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.

这篇关于使用 JAVA 在 Android Studio 中简单倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆