资源放到这里面来
图片来自百度。。。。你们也可以用别的图片
布局也很简单 一个图片 一个按钮
<?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:btnClick"
ohos:height="match_content"
ohos:text="点我"
ohos:text_size="150"
ohos:background_element="red"
ohos:width="match_parent"/>
</DirectionalLayout>
代码也很简单 批量添加进来然后随机即可
package com.example.helloworld.slice;
import com.example.helloworld.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 ChooseGirlFirendAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_choose_girl_firend);
ArrayList<Integer> list = new ArrayList<>();
list.add(ResourceTable.Media_img_1);
list.add(ResourceTable.Media_img_2);
list.add(ResourceTable.Media_img_3);
list.add(ResourceTable.Media_img_4);
list.add(ResourceTable.Media_img_5);
list.add(ResourceTable.Media_img_6);
Image image = findComponentById(ResourceTable.Id_img);
Button btnCick = findComponentById(ResourceTable.Id_btnClick);
btnCick.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
Random r = new Random();
int i = r.nextInt(list.size());
int randomIndex = list.get(i);
image.setImageAndDecodeBounds(randomIndex);
}
});
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
总结:
image.setImageAndDecodeBounds(图片的资源ID);