Reputation: 43
In Android, I have only found answers as to how to open a single specific Drawable
from MainActivity.java
, but not how to iterate over each Drawable
from res/drawables
. The Drawable
s names do not follow any patterns (e.g. being numbered from 0 to 25), so the answer suggested here sadly doesn't solve my problem. Does anyone know how to do the latter?
Thank you in advance :)
Upvotes: 2
Views: 1891
Reputation: 97
The easiest way to do it is to put the names of your drawables in a String array:
String[] symbols = {"first_img", "second_img", "third_img", "fourth_img"};
Then iterate over them like this (I put the images into a GridLayout):
for(String symbol : symbols) {
int id = getResources().getIdentifier(symbol, "drawable", getPackageName());
ImageView img = new ImageView(this);
LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams(300, 300);
imgParams.setMargins(30, 30, 30, 30);
img.setLayoutParams(imgParams);
img.setBackgroundResource(id);
symbolGrid.addView(img);
}
Upvotes: 1
Reputation:
If you want to iterate through drawables that have similar names like: image1, image2, ..., image10 you can do it like this:
for (int i = 0; i < 10; i++) {
int id = getResources().getIdentifier("image" + i, "drawable", getPackageName());
Drawable d = ContextCompat.getDrawable(this, id);
// your code here
}
Upvotes: 1
Reputation: 290
First, put your drawables into an arrays
<array name="dashboard_item_menu_drawable">
<item>@drawable/ic_file_green</item>
<item>@drawable/ic_email_green</item>
<item>@drawable/ic_linear_scale_green</item>
<item>@drawable/ic_undo_green</item>
<item>@drawable/ic_check_circle_green</item>
<item>@drawable/ic_archive_green</item>
</array>
Then, iterate your array drawables
val icons = ArrayList<Int>()
val arr = resources.obtainTypedArray(R.array.dashboard_item_menu_drawable)
(0 until arr.length()).forEach {
// get resource id of each drawable
val icon = arr.getResourceId(it, -1)
icons.add(icon)
}
Next, recycles resource
arr.recycle()
Then you can use your drawable
iconView.setImageDrawable(ContextCompat.getDrawable(this, icons[index]))
Upvotes: 2