0
点赞
收藏
分享

微信扫一扫

HarmonyOS3.0点赞事件

非凡兔 2022-01-12 阅读 37

首先在xml中创建页面

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    ohos:id="$+id:d1"//因为后面点赞双击需要在屏幕中点赞,所以添加一个屏幕的布局id为后面找到布局对象做准备
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

   <Image
       ohos:id="$+id:img"
       ohos:height="match_content"
       ohos:width="match_content"
       ohos:image_src="$media:white"
       ohos:background_element="cyan"//最开始是空白爱心,为了更好展示,加一个背景颜色
       />

</DirectionalLayout>

运行得到图片:
点赞界面
接着在MainAbilitySlice中进行编译点赞事件

package com.example.myapplication.slice;

import com.example.myapplication.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.DirectionalLayout;
import ohos.agp.components.Image;

public class MainAbilitySlice extends AbilitySlice implements Component.DoubleClickedListener {
    Image image;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        //1. 找到图片组件
        image = (Image)findComponentById(ResourceTable.Id_img);
        //有屏幕才能点赞,所以先找到铺面屏幕的布局对象
        DirectionalLayout dir = (DirectionalLayout)findComponentById(ResourceTable.Id_d1);
        //选中dir变量,按Alt+enter,选中split就可以将变量分离,如下:

        //DirectionalLayout dir;
        //dir = (DirectionalLayout)findComponentById(ResourceTable.Id_d1);

        //2. 给布局对象添加事件
        dir.setDoubleClickedListener(this);
        //单击图片对象取消点赞
        image.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Image image2 =(Image)component ;
                image2.setImageAndDecodeBounds(ResourceTable.Media_white);
            }
        });
    }


    /*
    两种情况,第一是双击屏幕点赞,再次双击就取消点赞,另一种是双击点赞,单击爱心图片取消点赞
     */
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
    //boolean flag=false;
    //如果是白心,为FALSE,则双击点赞后变为红心
    //如果是红心,为TRUE,则双击点赞后变为白心
    @Override
    public void onDoubleClick(Component component) {
        //修改图片为红色的心
        /*if(flag){
            image.setImageAndDecodeBounds(ResourceTable.Media_white);
            flag=false;
        }
        else{*/
            image.setImageAndDecodeBounds(ResourceTable.Media_red);
            //flag=true;
        //}

    }
}

展示结果
双击点赞
可以是代码运行出的双击点赞,单击爱心取消点赞的情况;
也可以是注释中的双击点赞,双击取消的情况。

举报

相关推荐

0 条评论