鸿蒙学习笔记之长按事件(八)

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

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

接下就直接开始操作代码了,创建完项目,然后我们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下载]

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

✎﹏ℳ๓敬坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值