how to select from resources randomly (R.drawable.xxxx)

前端 未结 8 944
终归单人心
终归单人心 2021-02-03 14:23

I want to display a random image from the bunch of images i have stored in res/drawable.

The only technique that I know is to access a particular image if you know its r

8条回答
  •  悲哀的现实
    2021-02-03 14:40

    I did this in my Applez application as follows;

    1) create an ArrayList to hold images and fill it 2) take random number and return corresponding image.

    in code :

    public static void fruitInventory() {
    fruitResources.clear();
    Field[] fields = R.drawable.class.getFields();
    
    for (Field field : fields) {
        // Take only those with name starting with "fr"
        if (field.getName().startsWith("fr_")) {
            try {
                String FType = field.getName().substring(3);
    
                fruitResources.add(field.getInt(null));
                alfruitTypes.add(FType);
                Log.d("FruitManager", "Type " + FType);
    
            } catch (IllegalArgumentException e) {
    
                e.printStackTrace();
            } catch (IllegalAccessException e) {
    
                e.printStackTrace();
            }
        }
    
    
    }
    

    and to add the fruit :

    public static void addFruit(Context context){
    
    fruitInventory();
    
    for (int i = 0; i < 10; i++) {
    Random Rnd = new Random();
    int FruitType = Rnd.nextInt(fruitResources.size());
    GameObject nextApple = new GameObject(BitmapFactory.decodeResource(context.getResources(),
                      fruitResources.get(FruitType)), FruitType);
    
    MainGamePanel.AppleList.add(nextApple);
    }
    

    }

    Idea was (and works) that I could add extra fruits to the game, simply by adding for instance "fr_eggplant.bmp" to the images folder.

提交回复
热议问题