中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
在一定的时间内点击按钮,点击按钮的次数就会记录到 Text 文本中
案例实现:
新建项目:StatisticsApplication
ability_main
<?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="$string:mainability_HelloWorld" 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" > </Button> </DirectionalLayout>
MainAbilitySlice
package com.xdr630.statisticsapplication.slice; import com.xdr630.statisticsapplication.ResourceTable; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Component; import ohos.agp.components.Text; public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener { Text text1; Button but1; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); //找到组件 text1 = (Text) findComponentById(ResourceTable.Id_text1); but1 = (Button) findComponentById(ResourceTable.Id_but1); //给按钮设置单击事件 but1.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++; //统计10s之类,按了多少次,并把次数展示在文本框 if (flag){ //如果当前是第一次点击按钮,记录当前的时间 startTime = System.currentTimeMillis(); //当第一次点击之后游戏开始,修改按钮中的文字内容 but1.setText("请疯狂点我"); //修改标记,当第二次调用onClick方法时,flag为false,表示第二次点就不是第一次了,就会走else里的代码 flag = false; }else{ if ((System.currentTimeMillis() - startTime) <= 10000){ text1.setText(count + ""); }else { but1.setText("结束"); //取消按钮点击事件,让该按钮不能被点击了 but1.setClickable(false); } } } }
微信扫码分享