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?
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
Kotlin
private fun getAllDrawables(): List<Drawable?> {
return R.drawable::class.java.fields.map {
ResourcesCompat.getDrawable(resources, it.getInt(null), null)
}
}