I have 10 image views:
ImageView Card0=(ImageView)findViewById(R.id.Card0);
.....
ImageView Card9=(ImageView)findViewById(R.id.Card9);
all images are in my drawable folder but I am selecting the card from remote database. a php script generates 10 random cards.
I have the array containing the file name:
Cards = deal.split(":");
Now I want to set the image:
Card0.setImageResource(R.drawable.Cards[0]);
I've tried and searched a lot but could not set any variable setImageResource(R.drawable.*Variable*);
someone plz help.
It is not possible to dynamically load using R.id.drawable.*.
Solution 1:
I will assume the names of yours card images are: card0.png, card1.png ... card9.png
I suggest you create an assets
directory (inside the res
directory). Copy the card images to the assets
directory.
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import java.io.InputStream;
import java.io.IOException;
public class YourActivity extends Activity {
//...
public Drawable loadAssetImage(String fileName) {
AssetManager assetMgr = this.getAssets();
try {
InputStream is = assetMgr.open(fileName);
Drawable d = Drawable.createFromStream(is, null);
return d;
}catch( IOException e ) {
// error...
return null;
}
}
}
The loadAssetImage()
method loads an image from the assets
directory. So, now you can dynamically load your images since it accepts string parameters.
Note that the directory name MUST BE assets
. Android allows direct (raw) access to internal resources in the assets
directory.
Solution 2
public Drawable loadCardImage(int index) {
switch( index ) {
case 0:
return android.R.Card0;
case 1:
return android.R.Card1;
..
case 9:
return android.R.Card9;
}
return null;
}
You would receive the indices of the cards from the server. This function would return the appropriate resource.