鸿蒙学习笔记之长按事件

之前学习了单击事件,双击事件,今天继续实操一下长按事件。那长按事件有什么作用呢?

长按事件的使用场景有:复制,显示遮罩层等,都会用到长按。

接下就直接开始操作代码了,创建完项目,然后我们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:height="match_content"
        ohos:width="match_content"
        ohos:id="$+id:btn"
        ohos:background_element="blue"
        ohos:text_color="white"
        ohos:text="长按按钮"/>
</DirectionalLayout>

接下来来写我们的长按事件:

Tips:

刚开始我们写长按事件时代码如下:

如上,我们发现这里并没有设置我们ui页面。

那如何快速生成ui页面呢,我们点击MainAbilitySlice然后Ctrl+B就可以快速设置ui页面了,设置完ui页面如下:

 这个时候ui页面就设置好了

 那我们如何写长按事件呢?

1.根据组件id找到我们的长按按钮

2.给长按按钮绑定长按事件

3.重写长按事件

具体代码如下:

package com.example.mydemolongclick.slice;

import com.example.mydemolongclick.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.LongClickedListener{
    private Text txt;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Button btn = (Button) findComponentById(ResourceTable.Id_btn);
        txt=(Text) findComponentById(ResourceTable.Id_text_helloworld);
        btn.setLongClickedListener(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onLongClicked(Component component) {
        txt.setText("页面长按了");
    }
}

当我们写完代码,具体效果如下:

长按前: 长按后:

 这样子我们就完成一个长按事件的实现!

需要源代码点击下载[HarmonyOS长按事件源代码.zip-其它文档类资源-CSDN下载]

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

猜你喜欢

转载自blog.csdn.net/qq_44291585/article/details/121607104