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

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

    If you knew you had X images to choose from could use random.nextInt(X) to randomly generate an integer between 0 (inclusive) and X (exclusive), then switch on it to pick your resource:

    Random mRand = new Random();
                int x = mRand.nextInt(8);
                switch (x) {
                case 0:
                    mResource = R.id.someresource1
                case 1:
                    mResource = R.id.someresource2
                ...
                case X:
                    mResource = R.id.someresourceX
    
                }
    

提交回复
热议问题