计时器demo
通过UI线程更新,实现计时器功能
java文件
package com.jinyou.basetest;
import com.jinyou.basetest.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import java.util.Timer;
import java.util.TimerTask;
public class MainAbility extends Ability {
//计时timer
private Timer timer;
//计时
private int count = 0;
//状态位
private boolean flag = true;
//开始按键,回0按键
private Button btn_zan, btn_o;
//时间文本
private Text text;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setMainRoute(MainAbilitySlice.class.getName());
super.setUIContent(ResourceTable.Layout_ability_main);
//控件初始化
btn_zan = (Button) findComponentById(ResourceTable.Id_btn1);
btn_o = (Button) findComponentById(ResourceTable.Id_btn2);
text = (Text) findComponentById(ResourceTable.Id_txt1);
btn_zan.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
getUITaskDispatcher().asyncDispatch(new Runnable() {
@Override
public void run() {
if (flag) {
createTimer();
btn_zan.setText("暂停");
} else {
timer.cancel();
timer = null;
btn_zan.setText("继续");
}
flag = !flag;
}
});
}
});
btn_o.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
if (timer != null)
timer.cancel();
timer = null;
count = 0;
getUITaskDispatcher().asyncDispatch(new Runnable() {
@Override
public void run() {
text.setText("" + count);
btn_zan.setText("开始");
}
});
}
});
}
//开始计时
private void createTimer() {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
count++;
getUITaskDispatcher().asyncDispatch(new Runnable() {
@Override
public void run() {
text.setText("" + count);
}
});
}
}, 0, 1000);
}
}
xml文件,通过线性布局实现
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<Text
ohos:id="$+id:txt1"
ohos:height="150vp"
ohos:width="match_parent"
ohos:left_margin="80vp"
ohos:text_size="50fp"/>
<Button
ohos:id="$+id:btn1"
ohos:height="60vp"
ohos:width="match_parent"
ohos:background_element="$graphic:background_ability_main"
ohos:text="开始"
ohos:text_size="50vp"
/>
<Button
ohos:id="$+id:btn2"
ohos:height="60vp"
ohos:width="match_parent"
ohos:background_element="$graphic:background_ability_main"
ohos:text="回0"
ohos:text_size="50vp"
ohos:top_margin="30vp"
/>
</DirectionalLayout>
运行效果
1
2