4

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?

Mauker
  • 11,237
  • 7
  • 58
  • 76
Mihail Boiarskii
  • 325
  • 2
  • 4
  • 16

3 Answers3

13

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);
}
Mauker
  • 11,237
  • 7
  • 58
  • 76
7
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

d0nut
  • 2,835
  • 1
  • 18
  • 23
0

Kotlin

    private fun getAllDrawables(): List<Drawable?> {
        return R.drawable::class.java.fields.map {
            ResourcesCompat.getDrawable(resources, it.getInt(null), null)
        }
    }
YaMiN
  • 3,194
  • 2
  • 12
  • 36