Reputation: 121
I placed 10 images in drawable folder and I created a custom class which instances are holding an id Integer that should refer it to a image from draw folder. Now I wonder how to set those id-s at once, not one by one. Instead:
object[0].setImage(R.drawable.image1);
object[1].setImage(R.drawable.image2);
I want to do this with loop, but how?
Upvotes: 1
Views: 894
Reputation: 79
You can create an integer array for the resources:
int resources = [ R.drawable.image1, R.drawable.image2, ...]
And use a bucle to set the resources into your object array.
Upvotes: 0
Reputation: 2840
Drawable
ids as known are generated within static classes of final class R
. So just use reflection to read the values of these static attributes. If you want to get the Int ids then use this code:
for(Field f : R.drawable.class.getDeclaredFields()){
if(f.getType() == int.class){
try {
int id = f.getInt(null);
// read the image from the id
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e){
e.printStackTrace();
}
}
}
Or if you want to search directly by images' names, you might be interested of the name attribute of fields like :
for(Field f : R.drawable.class.getDeclaredFields()){
if(f.getType() == int.class){
try {
String name = f.getName();
// rest of the code handling file loading
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
Upvotes: 2
Reputation: 8293
Be aware that the size of the view's list should match with the one that holds the ids:
public class HolderIDs {
public List<Integer> _ids;
public HolderIDs() {
_ids = new ArrayList<Integer>(Arrays.asList(R.drawable.one, R.drawable.two, R.ldrawable.three, R.drawable.four));
}
public List<Integer> getIDs() {
return _ids;
}
}
//Usage
List<ImageView> views = getYourViews();
List<Integer> ids = new HolderIDs().getIDs();
for (int i = 0; i < ids.size(); i++) {
View view = views.get(i);
if (view == null) return;
int id = ids.get(i);
view.setBackgroundResource(id);
}
Upvotes: 0
Reputation: 209
Doesn't work as far as I think.
There is code to get a drawable by its name. For example: "image"+myNumber"
Maybe: how to access the drawable resources by name in android
Upvotes: 1