鸿蒙开发中,关于60s倒计时的使用示例?
在鸿蒙(HarmonyOS)开发中,你可以使用多种方式实现倒计时功能。以下是一个基本的倒计时示例,展示了如何使用Handler和Runnable来创建一个简单的倒计时器。
假设你正在使用Java来进行开发,以下是一个示例代码:
java
复制代码
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
java
复制代码
public class MainAbilitySlice extends AbilitySlice {
private Text countdownText;
private EventHandler eventHandler;
private int countdownTime = 10; // 倒计时时间,单位为秒
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
countdownText = (Text) findComponentById(ResourceTable.Id_countdown_text);
eventHandler = new EventHandler(EventRunner.getMainEventRunner());
startCountdown();
}
private void startCountdown() {
eventHandler.postTask(new Runnable() {
@Override
public void run() {
if (countdownTime > 0) {
countdownText.setText(String.valueOf(countdownTime));
countdownTime--;
eventHandler.postTask(this, 1000); // 每隔1秒执行一次
} else {
new ToastDialog(getContext()).setText("倒计时结束").show();
}
}
});
}
}
xml
复制代码
<!-- ability_main.xml -->
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:orientation="vertical"
ohos:alignment="horizontal_center"
ohos:gravity="center">
<Text
ohos:id="$+id:countdown_text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text_size="50vp"
ohos:text="10" />
</DirectionalLayout>