首先把需要用到的图片放入media文件夹
修改ability_main.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">
<Image
ohos:id="$+id:img"
ohos:height="match_content"
ohos:width="match_content"/>
<Button
ohos:id="$+id:but1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="点我"
ohos:text_size="150"
ohos:background_element="#FFE38585"/>
</DirectionalLayout>
MainAbilitySlice.java整体代码:
package com.example.listenapplicantion8.slice;
import com.example.listenapplicantion8.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 {
Image image;
ArrayList<Integer> list = new ArrayList<>();
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1.定义一个数组或集合用来存储所有图片,这里用集合,因为数组还要确定大小比较麻烦
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);
//2.找到对应组件
image = (Image) findComponentById(ResourceTable.Id_img);
Button but1 = (Button) findComponentById(ResourceTable.Id_but1);
//3.给按钮绑定单击事件
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组件
image.setImageAndDecodeBounds(randomImg);
}
}