計時器demo
通過UI線程更新,實現(xiàn)計時器功能
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;
//狀態(tài)位
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("繼續(xù)");
}
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文件,通過線性布局實現(xiàn)
<?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

image.png
2

image.png