实现效果
10秒统计次数
代码实现
ability_main.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:alignment="center"
ohos:orientation="vertical">
<Text
ohos:id="$+id:text1"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text= "Hello World"
ohos:text_size="40vp"
/>
<Button
ohos:id="$+id:but1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="开始"
ohos:text_size="100"
ohos:background_element="red"
/>
</DirectionalLayout>
MainAbilitySlice.java
package com.example.myapplication.slice;
import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.OnClickListener;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.javax.xml.stream.events.EndElement;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
Button btu1;
Text text;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1. 找到文本,按钮的对象
btu1 = (Button) findComponentById(ResourceTable.Id_but1);
text = (Text) findComponentById(ResourceTable.Id_text1);
//给按钮去设置单击事件
btu1.setClickedListener(this);
}
@Override
public void onActive() { super.onActive(); }
@Override
public void onForeground(Intent intent) { super.onForeground(intent);}
//如果flag为true表示当前按钮是第一次点击
//如果flag为false表示当前按钮不是第一次点击
boolean flag = true;
long startTime = 0;
//用来记录点击了多少次
int count = 0;
@Override
public void onClick(Component component) {
//点一次,计数器就自增一次
count++;
//统计10秒之内按了多少次
//并把次数在文本框中显示出来
if (flag){
//如果当前是第一次点击按钮
//要记录当前时间
startTime = System.currentTimeMillis();
//当第一次点击之后,游戏开始
//修改按钮中文字内容
btu1.setText("请点击");
//修改标记
flag = false;
}else {
if ((System.currentTimeMillis() - startTime) <= 10000){
text.setText(count + "");
}else {
btu1.setText("结束");
//取消按钮的点击事件,让按钮不能再点击
btu1.setClickable(false);
}
}
}
}