鸿蒙学习笔记之双击事件

昨天学习了点击事件的四种实现方法,在我们平常使用APP的过程中,我们都知道除了点击事件,还有很多其他的事件,比如双击事件,长按事件,滑动事件等。然后我们今天会学习如何使用双击事件

 话不多说,今天就直接上代码了,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:text_helloworld"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:background_element="$graphic:background_ability_main"
        ohos:layout_alignment="horizontal_center"
        ohos:text="我是双击事件页面"
        ohos:text_size="40vp"
        />
    <Button
        ohos:id="$+id:btn1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="我是双击按钮"
        ohos:background_element="red"/>

</DirectionalLayout>

当我们写完页面代码之后,效果如下:

然而,这就结束了嘛,并没有,当我们写完页面,还要继续写如何实现这个双击事件,接下就是展现真正的技术了,事件代码如下:

package com.example.mydemodoubleclick;

import com.example.mydemodoubleclick.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;

public class MainAbility extends Ability implements Component.DoubleClickedListener {
    private Text txt;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        super.setUIContent(ResourceTable.Layout_ability_main);
        //找到text标签
        txt = findComponentById(ResourceTable.Id_text_helloworld);
        //还是一样第一步我们先找到我们的双击按钮
        Button btn1 = (Button)findComponentById(ResourceTable.Id_btn1);
        btn1.setDoubleClickedListener(this);
    }

    @Override
    public void onDoubleClick(Component component) {
        txt.setText("触动了双击事件");
    }
}

这个实现我们xml和事件就写完了,当我们双击了按钮之后,页面效果如下:

 关于双击事件,今天就讲到这里了,大家要代码的可以在这里点击HarmonyOS的双击事件实现源代码.rar-其它文档类资源-CSDN下载下载源代码!

Tips:

当我们创建完项目之后,会发现在Java代码中并没有super.setUIContent()这个方法,我们还没有绑定事件的时候,运行代码是可以正常显示页面的,但是给按钮绑定事件之后,就会发现怎么运行都运行不了,或者出现闪退的情况。这个时候将super.setUIContent()添加进去就可以正常运行了

 

分享不易,都观看到这里了,还不点赞收藏吗!

 

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>