当前位置:   article > 正文

HarmonyOS应用开发基础——点击事件的绑定_鸿蒙os ets 绑定事件

鸿蒙os ets 绑定事件

HarmonyOS应用开发基础——点击事件的绑定

点击事件的四种写法

首先在ability_main.xml中添加一个Button和Text`

 <Button
        ohos:id="$+id:but1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="点我"
        ohos:text_size="200"
        ohos:background_element="red"
        />
        <Text
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:id="$+id:text1"
        ohos:text="text"
        ohos:text_size="100"
        />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

第一种方法:定义实现类

首先我们需要去找到我们之前已经定义的button和Text,通过id查到
在最外层定义全局变量text1

Text text1=null;
  • 1
//1.找到按钮和文本框
Button but1=(Button)findComponentById(ResourceTable.Id_but1);
text1=(Text)findComponentById(ResourceTable.Id_text1);
  • 1
  • 2
  • 3

第二步便是绑定单击事件

//2.给按钮绑定单击事件
but1.setClickedListener(new MyListener());
  • 1
  • 2

在MainAbilitySlice.java文件中,自己创建一个类MyListener,实现接口 Component.ClickedListener

class MyListener implements Component.ClickedListener
{
   
    @Override
    public void onClick(Component component) {
   
        //component:所有组件的父类
        //参数:被点击的组件对象
        
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/282118
推荐阅读
相关标签
  

闽ICP备14008679号