> 文档中心 > HarmonyOS Image 图片的使用 随机选妹子

HarmonyOS Image 图片的使用 随机选妹子

资源放到这里面来

 图片来自百度。。。。你们也可以用别的图片

 

布局也很简单 一个图片 一个按钮

        

代码也很简单 批量添加进来然后随机即可

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 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);