简体   繁体   中英

How to get all Drawable resources?

How to get all Drawable resources and put them into ArrayList ?

I wanna make something like playing cards, put them into ArrayList and shuffle them. After that I wanna give players cards. What is the best way to do it?

To iterate through your drawables, you can use the Field class.

Try something like the following:

Field[] drawablesFields = com.your.project.R.drawable.class.getFields();
ArrayList<Drawable> drawables = new ArrayList<>();

for (Field field : drawablesFields) {
    try {
        Log.i("LOG_TAG", "com.your.project.R.drawable." + field.getName());
        drawables.add(getResources().getDrawable(field.getInt(null)));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Or you could also use the assets folder. Put your images inside a sub-directory called images , and the use the AssetManager class to get those files. This is an approach that is not project-specific .

Try something like:

AssetManager am = context.getAssets();
String[] files = am.list("images");
InputStream istr = null;
ArrayList<Drawable> drawables = new ArrayList<>();

for (String file : files) {
    Drawable d = Drawable.createFromStream(am.open(file), null);
    drawables.add(d);
}
Field[] drawables = com.example.myapp.R.drawable.class.getFields();

ArrayList<Drawable> drawableResources = new ArrayList<>();

for(Field field : drawables)
{
    //drawable's id added to arraylist
    drawableResources.add(getResources().getDrawable(field.getInt(null)));
}

drawableResources will now contain each drawable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM