Android ImageView setImageResource in code - android

I have an imageView that I want to display a little icon of the country that you are currently in. I can get the country code, but problem is I can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)
My code (countryCode is the current countryCode in uppercase letters):
String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);
Now, of course this will not work because setImageResource wants an int, so how can I do this?

One easy way to map that country name that you have to an int to be used in the setImageResource method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.

This is how to set an image into ImageView using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);

you use that code
ImageView[] ivCard = new ImageView[1];
#override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);

You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));

you may try this:-
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));

Related

Dynamically choosing drawable

I want the user to select a wallpaper and I'll set it as the android wallpaper.
I'm currently using this line:
myWallpaperManager.setResource(R.drawable.a1);
Problem is it's not dynamic and I want to change the chosen image to R.drawable.a2,R.drawable.a3,R.drawable.a4, etc based on the number I got.
So if I have int chosenPicNum=3 I want to create the string "R.drawable.a"+3 and then call myWallpaperManager.setResource(R.drawable.a3);
But I can't do it. The error is eclipse reads it as a string and not a resource.
Currently here's the closest I've gotten:
String imageResource="R.drawable.a"+chosenPicNum) ;
So imageResource in this case is String type "R.drawable.a3" but I want it to be R.drawable.a3.
Thank you for your help!!
Dvir, ambitious 20 year old :)
Use getIdentifier() like this:
public final static String PACKAGE = "..."; // insert your package name
private int getDrawable(String name) {
return getId(name, "drawable");
}
private int getId(String name, String type) {
return getResources().getIdentifier(name, type, PACKAGE);
}
Access the method using:
myWallpaperManager.setResource(getDrawable("a" + chosenPicNum));
As you use resources, you already know their number and names. So use an array:
int[] ids = new int[] {R.drawable.a1, R.drawable.a2, R.drawable.a3, };
And when you have your chosenNumPic (assuming it's 0 based):
if (chosenNumPic >= 0 && chosenNumPic < ids.length) {
myWallpaperManager.setResource(ids[chosenNumPic]);
}
Hope it helps :)
try this
int resId = getResources().getIdentifier("your_drawable_name"), "drawable", getActivity().getPackageName());
imageview.setBackgroundResource(resId);

Creating Dynamic R.drawable source and ImageView

I have an Activity which has variable position that comes from another activity. I handle this variable with Intent like below. (Actually position is listView's position from another activity.) and values of position variable are 0 to 200
I took my Extra, then assigned it to a string than I parsed it to an Integer. These are normal and easy for me and working.
Intent i = getIntent();
String position = i.getStringExtra("POSITION");
int position_to_int = Integer.parseInt(position);
But my problem is about resources.
Simply I want to put an image to my LinearLayout dynamically . I have some country flags and they named in format like 0.gif, 1.gif, 2.gif, 3.gif ...
My idea is using position variable's value for this purpose.
but when I try to use position_to_int variable for name of flag, Eclipse returning error normally. Because R.drawble.XXX values storing in R.java
ImageView imageView = new ImageView(this);
// setting image resource
imageView.setImageResource(R.drawable.position_to_int);
How can I use position_to_int variable to show an ImageView dynamically?
You can't access it directly. You'll have to get the resource using its name:
private Drawable getDrawableResourceByName(int name) {
String packageName = getPackageName();
int resId = getResources().getIdentifier("character_you_prefixed" + String.valueOf(name), "drawable", packageName);
return getResources().getDrawable(resId);
}
Note that your resource names must begin with a letter, not a number, or else your project will not compile. Try adding a character to the beginning of each file name.

Reference to R.drawabe dynamically?

I got about 200+ Country names in my app.
I got 200+ flag icons for each country.
The flag icons names are equals the country names, so like:
Country name: ENG, icon name eng.png
I want to make a list of them in my app to select country.
I dont want to build the layout by manually and add 200+ icons for each and every TextView...
My question is, can i add dynamically somehow ?
Something like this:
private void setIcon(String iconName)
{
countryIcon.setBackgroundResource(R.drawable. /* and i need the magic here*/ +iconName )
}
So can i reference to R.drawable dynamically by somehow with param?
Try this:
private void setIcon(String iconName) {
Resources res = getResources();
int imageResource = res.getIdentifier("drawable/" + iconName, null, getPackageName());
Drawable image = res.getDrawable(imageResource);
countryIcon.setBackgroundResource(image);
}
If you've a pattern, is not difficult at all.
Here's an example. I did this for loading flag-images in a ListView depending the flag IDs of each row-object. Once i've the language_id i get the language_KEY (String) which is the same as my icon's name:
int ico_id, int visible=View.visible();
String flag;
Bitmap icona;
flag= (MyWharehouse.getLangKey(language_id.get(position))).toLowerCase(); //get the image.png name
ico_id = a.getResources().getIdentifier(flag, "drawable", a.getString(R.string.package_str));
icona = BitmapFactory.decodeResource(a.getResources(), ico_id);
((ImageView)a.findViewById(R.id.im_lang_01)).setImageBitmap(icona); //changing the image

Handle drawables - by the name

I already know how to handle drawables like this:
final int[] imgSizeIds = new int[]{
R.drawable.zero,R.drawable.one,R.drawable.two,
...
};
and
setImageResource(imgSizeIds [ size ] );
in android. But what If I have an Array of Strings that is populated like this:
String[] names = new String[]{"oliver", "peter", "mike"};
and I would like to use Image oliver.jpg when The ROW Oliver is going to be handled.
Something like:
setImageResource(R.drawable. (AND HERE COMES "oliver") );
So the result will be:
setImageResource(R.drawable.oliver);
Two Arrays would not be the big problem but I also do not know how to put a string into the integer Array of drawables.. I cannot do something like:
final int[10] imgSizeIds;
String stringy = "oliver";
int[0] = "R.drawable." + stringy;
So that the 1st item in that array would be set to R.drawable.oliver
try this
int resid = getResources.getIdentifier("oliver" , "drawable", getPackageName());
setImageResource(resid);
setImageResource(R.drawable. (AND HERE COMES "oliver") );
So the result will be: setImageResource(R.drawable.oliver);
this will probably not happen.Because when you tell android to take a string specified in a String variable,it would take it as - "oliver" and put it like R.drawable."oliver" or even though,if you would try putting it like - setImageResource("R.drawable."+ (AND HERE COMES "oliver") ) it will take it as a String like "R.drawable.oliver" which is after all a String variable and not appropriate to be passed in setImageResource() method.
Be sure that R.drawable.imagename gives you int, not a string.
See if below code helps-
String[] imgNames = new String[]{ "oliver", "apple", "car"};
and use this to use names from name string array-
ImageView imgvw = (ImageView) findViewById(getResources().getIdentifier(imgNames[index],"drawable",getPackageName()));
where index is position of item in string name array.

Changing image view background dynamically

I have a a set of 10 imageviews in my layout. I have given them sequential id's also as
android:id="#+id/pb1"
android:id="#+id/pb2"
Now I want to change background dynamically.
int totalPoi = listOfPOI.size();
int currentPoi = (j/totalPoi)*10;
for (i=1;i<=currentPoi;i++) {
imageview.setBackgroundResource(R.drawable.progressgreen);
}
Now inside the for loop I want to set the image view background dynamically. i,e if the currentpoi value is 3, background of 3 image views should be changed. What ever the times the for loop iterates that many image view's background should be changed. Hope the question is clear now.
Note : I have only 1 image progressgreen that need to be set to 10 image views
Finally I did this in the following way,
I placed all the id's in the array as
int[] imageViews = {R.id.pb1, R.id.pb2,R.id.pb3,R.id.pb4,R.id.pb5,R.id.pb6,R.id.pb7,R.id.pb8,R.id.pb9,R.id.pb10};
Now:
int pindex = 0;
for (pindex; pindex <currentPoi; pindex++) {
ImageView img = (ImageView) findViewById(imageViews[pindex]) ;
img.setImageResource(R.drawable.progressgreen);
}
Now, I am able to change the images dynamically.
#goto10. Thanks for your help. I will debug your point to see what went wrong in my side
Create an ImageView array:
ImageView views[] = new ImageView[10];
views[0] = (ImageView)findViewById(R.id.pb1);
...
views[9] = (ImageView)findViewById(R.id.pb10);
Now iterate the loop to set the background of images like this:
for (i=1;i<=currentPoi;i++)
{
views[i-1].setBackgroundResource(R.drawable.progressgreen);
}
you can do this by setting the name of drawables something like:
img_1, img_2, img_3...
for (i=1;i<=currentPoi;i++)
{
ImageView imageview=(ImageView) findViewById(getResources().getIdentifier("imgView_"+i, "id", getPackageName()));
imageview.setImageResource(getResources().getIdentifier("img_"+i, "drawable", getPackageName()));
}
Try this code.....
Create image Array..
private Integer[] mThumbIds = { R.drawable.bg_img_1, R.drawable.bg_img_2,
R.drawable.bg_img_3, R.drawable.bg_img_4, R.drawable.bg_img_5 };
And than modify your code
int totalPoi = listOfPOI.size();
int currentPoi = (j/totalPoi)*10;
for (i=1;i<=currentPoi;i++) {
imageview.setBackgroundResource(mThumbIds[i]);}
You could make an array of your ImageViews and then change them in your for loop.
ImageView views[] = new ImageView[10];
views[0] = (ImageView)findViewById(R.id.imageView0);
...
views[9] = (ImageView)findViewById(R.id.imageView9);
and then change your for loop to:
for (i=1;i<=currentPoi;i++) {
views[currentPoi].setBackgroundResource(R.drawable.progressgreen);
}
Arrays start at index 0, so make sure there's not an off-by-one error in here.
You'll need to give your ImageViews sequential ids, such as "#+id/pb1" and "#+id/pb2", etc.. Then you can get each of them in the loop like this:
for (i=1;i<=currentPoi;i++) {
// Find the image view based on it's name. We know it's pbx where 'x' is a number
// so we concatenate "pb" with the value of i in our loop to get the name
// of the identifier we're looking for. getResources.getIdentifier() is able to use
// this string value to find the ID of the imageView
int imageViewId = getResources().getIdentifier("pb" + i, "id", "com.your.package.name");
// Use the ID retrieved in the previous line to look up the ImageView object
ImageView imageView = (ImageView) findViewById(imageViewId);
// Set the background for the ImageView
imageView.setBackgroundResource(R.drawable.progressgreen);
}
Replace com.your.package.name with your application's package.

Categories

Resources