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

前端 未结 8 1134
终归单人心
终归单人心 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:47

    I realize this is a super old question, but wanted to provide a good solution for any Googlers.

    Access resources by name is much less efficient than by id. The whole point of the resource system is so that you don't have to resolve names, and can use ids instead.

    What you need to do is utilize the Array Resource type. Follow along with my easy steps! I make random images...Fun!

    1. Create an array resource that includes all of the images you want to choose from. I put this in my res/values/arrays.xml file but it can really go anywhere.

      
          @drawable/bg_loading_1
          @drawable/bg_loading_2
          @drawable/bg_loading_3
          @drawable/bg_loading_5
          @drawable/bg_loading_6
          @drawable/bg_loading_7
          @drawable/bg_loading_8
      
      
    2. Next, get the TypedArray from the Resources and use that to choose a random image.

      TypedArray images = getResources().obtainTypedArray(R.array.loading_images);
      int choice = (int) (Math.random() * images.length());
      mImageView.setImageResource(images.getResourceId(choice, R.drawable.bg_loading_1));
      images.recycle();
      
    3. Profit!

提交回复
热议问题