Issue
Is there a way to use a counter in a java file to set a resource/drawable/image to a variable?
For instance:
Layout file
<ImageView
android:id="@+id/imageHolder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>
Java file
int index = 0;
ImageView imgHolder =(ImageView) findViewById(R.id.imgHolder);
Drawable drawable = getResources().getDrawable(R.drawable.img<index>);
imgHolder.setImageDrawable(drawable);
I'm sure this isn't possible like this, but I just wanted to give an example of what I'm trying to accomplish.
I would just want to get around what I feel is inevitable, ie:
if(index == 1)
{
drawable = getResources().getDrawable(R.drawable.img1);
imgHolder.setImageDrawable(drawable);
}
else if(index == 2)
{
drawable = getResources().getDrawable(R.drawable.img2);
imgHolder.setImageDrawable(drawable);
}
else if(index == 3)
etc...
Solution
Similar to my answer here How to add ImageView's that are depending on the text of the TextView in a ListView
image.setImageResource(getImageId(this, "img" + index);
So basically you're getting the number from your counter and manipulating it to be in the format you're storing your images and calling the below helper to get the correct image id.
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
Answered By - Lachlan Goodhew-Cook
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.