首先把需要用到的图片放入media文件夹
修改ability_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
ohos:id="$+id:dl"
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="#FF52E3E3"/>
</DirectionalLayout>
MainAbilitySlice.java整体代码:
package com.example.listenapplicantion6.slice;
import com.example.listenapplicantion6.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
public class MainAbilitySlice extends AbilitySlice implements Component.DoubleClickedListener, Component.ClickedListener {
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 dl = (DirectionalLayout) findComponentById(ResourceTable.Id_dl);
//2.给布局添加双击事件
dl.setDoubleClickedListener(this);
image.setClickedListener(this);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
//false:没点赞,双击会变红
//true:已点赞,双击会变白
boolean flag = false;
@Override
public void onDoubleClick(Component component) {
//修改图片
image.setImageAndDecodeBounds(ResourceTable.Media_red);
}
@Override
public void onClick(Component component) {
if (flag){
image.setImageAndDecodeBounds(ResourceTable.Media_white);
flag = false;
}else {
image.setImageAndDecodeBounds(ResourceTable.Media_red);
flag = true;
}
}
}