2021-01-26鸿蒙开发(七)

计时器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文件,通过线性布局实现




    

    

运行效果
1


image.png

2


image.png

你可能感兴趣的:(2021-01-26鸿蒙开发(七))