定时器开关在目前生活中也很常用,用于定时计算有限时间内干了多少事情。
- 其他注意:alt + shift + ↑或↓,用于调整代码上下移动
1、简单使用
通过使用的案例实现来分析定时器组件的使用方法
- 本次目标:用来个按钮(开始 和 结束)来操作定时器组件,以实现定时器开始计时和结束计时的操作
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">
<TickTimer
ohos:id="$+id:ticktimer"
ohos:height="match_content"
ohos:width="match_content"
ohos:text_size="30fp"
ohos:text_color="#FFFFFF"
ohos:background_element="#0000FF"
ohos:text_alignment="center"
ohos:layout_alignment="center"
/>
<Button
ohos:id="$+id:start"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="开始"
ohos:text_size="30fp"
ohos:text_color="#FFFFFF"
ohos:background_element="#666600"
ohos:text_alignment="center"
ohos:layout_alignment="center"
ohos:top_margin="30vp"
/>
<Button
ohos:id="$+id:end"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="结束"
ohos:text_size="30fp"
ohos:text_color="#FFFFFF"
ohos:background_element="#666600"
ohos:text_alignment="center"
ohos:layout_alignment="center"
ohos:top_margin="30vp"
/>
</DirectionalLayout>
Java业务逻辑实现:
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
TickTimer tickTimer = null;
Button start = null;
Button end = null;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1、找到组件
tickTimer = (TickTimer) findComponentById(ResourceTable.Id_ticktimer);
start = (Button) findComponentById(ResourceTable.Id_start);
end = (Button) findComponentById(ResourceTable.Id_end);
//2、按钮绑定事件
start.setClickedListener(this);
end.setClickedListener(this);
//3、定时器基本设置
//计时顺序设置:false正向计时(0,1,2);true反向计时
tickTimer.setCountDown(false);
//设置计时格式,默认格式: mm:ss
tickTimer.setFormat("mm:ss");
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
@Override
//参数代表被点击的按钮对象
public void onClick(Component component) {
if(component == start) {
//开始计时
tickTimer.start();
} else if(component == end) {
//结束计时
tickTimer.stop();
}
}
}
2、组件小bug
bug1:
bug1: 设置计时顺序后,如果是false并不会从0开始计时
- 计时顺序设置:false正向计时(0,1,2);true反向计时
- tickTimer.setCountDown(false);
bug2:
bug2:基准时间设置问题
- 设置基准事件(从那个时间开始计时),如果没有设置基准时间默认从原点时间开始计时
- 如果参数设置为0,表示从当前时间开始计时
- 如果参数设置为非0,只是对当前时间做了一个减少
- tickTimer.setBaseTime(xxx);
组件使用建议:
- 不要使用setBaseTime设置基准时间
- 计时器一旦结束后,就不要重新开始了(也即每个定时器只使用一次)