
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源
去关联
实现案例:
ImageSwitchApplication
思路分析:
text
文本里面的汉字就可以使用资源管理器,但是现在不需要图片里的每个字节,要的是图片的整体,就不需要用资源管理器去读了,直接用ResourceTable
来获取就行了int
类型的,所以集合用 Integer
onClick
方法当中要用到 img
组件对象、还要创建的集合对象,所以要把这两者定为成员变量,onClick
方法才能使用代码实现:
ability_main
<?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">
<Image
ohos:id="$+id:img"
ohos:height="match_content"
ohos:width="match_content">
</Image>
<Button
ohos:id="$+id:but1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="点我"
ohos:text_size="150"
ohos:background_element="red"
>
</Button>
</DirectionalLayout>
MainAbilitySlice
package com.xdr630.imageswitchapplication.slice;
import com.xdr630.imageswitchapplication.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.Image;
import java.util.ArrayList;
import java.util.Random;
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
ArrayList<Integer> list = new ArrayList<>();
Image img;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//定义一个数组或者集合来存储所有图片
list.add(ResourceTable.Media_girl1);
list.add(ResourceTable.Media_girl2);
list.add(ResourceTable.Media_girl3);
list.add(ResourceTable.Media_girl4);
list.add(ResourceTable.Media_girl5);
list.add(ResourceTable.Media_girl6);
list.add(ResourceTable.Media_girl7);
list.add(ResourceTable.Media_girl8);
list.add(ResourceTable.Media_girl9);
//找到组件
img = (Image) findComponentById(ResourceTable.Id_img);
Button but1 = (Button) findComponentById(ResourceTable.Id_but1);
//给按钮绑定单击事件
but1.setClickedListener(this);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
@Override
public void onClick(Component component) {
//当按钮被点击之后,需要修改图片的内容
Random r = new Random();
int index = r.nextInt(list.size());
//通过随机索引,可以获取随机元素
int randomImg = list.get(index);
//把获取到的随机图片设置给Image组件就可以了
img.setImageAndDecodeBounds(randomImg);
}
}