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

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

    You can also access resources by name, which may be a viable approach to solving your problem if you know the names of the resources or can derive them according to some pre-defined naming scheme.

    You have to map the name to the identifier using the getIdentifier method of the Resources class.

    String name = "resource" + rng.nextInt(count);
    int resource = getResources().getIdentifier(name, "drawable", "com.package");
    

    The documentation for this method says:

    Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

    This is true but need not be a problem if you are doing it in code that isn't performance sensitive.

    Alternatively, if you don't mind listing the resources in XML, you could create a typed array that you can then randomly select from.

提交回复
热议问题