回复
     HarmonyOS实现单击事件流程 原创
兮动人
 发布于 2021-7-26 21:26
 浏览
 1收藏
@[toc]
1. 什么是事件?
- 事件就是可以被识别的操作 。就是可以被文本、按钮、图片等组件识别的操作。
 - 常见的事件有:单击、双击、长按、还有触摸事件 。
 - 可以给文本、按钮等添加不同的事件。比如添加了单击事件之后,当我们再次点击文本、按钮,就可以运行对应的代码了。
 - 常见的事件有:

 
2. 单击事件(常用)
- 单击事件:又叫做点击事件。是开发中使用最多的一种事件,没有之一。
 - 接口名:ClickedListener,又叫:点击事件。
 - 如:当点击后,文字内容就会发送变化


 
3. 实现步骤
- 创建项目名为:ListenerApplication

 
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">
    <Button
        ohos:id="$+id:but1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="点我"
        ohos:text_size="200"
        ohos:background_element="red">
    </Button>
</DirectionalLayout>
MainAbilitySlice
package com.example.listenerapplication.slice;
import com.example.listenerapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        //1.找到按钮
        //完整写法:this.findComponentById(ResourceTable.Id_but1);
        //this:本类的对象,指:MainAbilitySlice(子界面对象)
        // 在子界面当中,通过 id 找到对应的组件
        // 用this去调用方法,this可以省略不写
        //findComponentById(ResourceTable.Id_but1);
        //返回一个组件对象(所以组件的父类对象)
        //那么我们在实际写代码的时候,需要向下转型:强转
        Component but1 = (Button) findComponentById(ResourceTable.Id_but1);
        //2.给按钮绑定单击事件,当点击后,就会执行 MyListener 中的方法,点一次执行一次
        // 而方法就是下面点击的内容
        but1.setClickedListener(new MyListener());
    }
    @Override
    public void onActive() {
        super.onActive();
    }
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
class MyListener implements Component.ClickedListener{
    @Override
    public void onClick(Component component) {
        //Component:所有组件的父类
        //component参数: 被点击的组件对象,在这里就表示按你的对象
        //component.setText(); setText是子类特有的方法,需要向下转型:强转
        Button but = (Button) component;
        but.setText("被点了");
    }
}
- 运行:

 - 点击后:

 
4. 小节
- 单击事件:又叫做点击事件。是开发中使用最多的一种事件,没有之一。
 - 实现步骤:
1.通过id找到组件。
2.给按钮组件设置单击事件。
3.写一个类实现ClickedListener接口并重写onClick方法。
4.编写onClick方法体。 
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
 分类 
    
        赞
        3
 
        收藏 1
      
 回复
  相关推荐
 



















