Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ImageView setImageResource in code

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?

like image 685
arielschon12 Avatar asked Sep 28 '12 19:09

arielschon12


People also ask

What is ImageView code?

Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling. To learn more about Drawables, see: Drawable Resources.

How do you set the content of an ImageView in your Java code?

ImageView imageView = new ImageView(this); imageView. setImageResource(R. drawable. beerbottle); RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.

How do I reset my image view?

This example demonstrates how do I clear an imageview in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.

How do you make a picture clear on android?

Go to the “Enhance” menu on the app's homescreen. The enhance function helps optimize your photos for enhanced facial features and a sharper background. It can help reduce noise and strange-looking pixels and works well on low-resolution and blurry photos. Click “use it” to proceed with the deblurring.


2 Answers

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.

like image 97
user Avatar answered Oct 08 '22 03:10

user


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); 
like image 44
Jorgesys Avatar answered Oct 08 '22 03:10

Jorgesys