帮我写一个安卓5秒倒计时
时间: 2023-06-19 11:03:13 浏览: 92
好的,你可以参考以下代码实现:
1. 创建一个新的 Android 项目
2. 在 layout 文件夹中创建一个新的布局文件 countdown.xml,内容如下:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/countdown_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
```
3. 在 MainActivity.java 中实现倒计时逻辑,代码如下:
```
public class MainActivity extends AppCompatActivity {
private TextView countdownText;
private CountDownTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown);
countdownText = findViewById(R.id.countdown_text);
startCountdown();
}
private void startCountdown() {
countDownTimer = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
countdownText.setText(String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
countdownText.setText("Done!");
}
}.start();
}
}
```
4. 运行程序,可以看到一个 5 秒的倒计时。
希望这个代码对你有所帮助!
阅读全文
相关推荐


















