Handle drawables - by the name - android

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.

Related

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.

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?
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));

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

Android String Not Equal

I am brand new to Java and Android so I am sure this will be an easy question/answer. I know that to find out if a string is equal to another string you use the equal function. In my situation, I am scanning a QR Code where the result of the scan is Similar to "EMPLOYEE~~John Smith~~DIVISION~~Maintenance". I need to know how to do the following:
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
// Do Something
}
In the example Java Code, myJunk[0] never equals val1. What am I doing wrong?
i've tried this and it works , so try to display the contents variable , probably the problem is in the extras , try to display it in logCat :
String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
}
Your string is:
EMPLOYEE~~John Smith~~DIVISION~~Maintenance
So after spliting, myJunk[0] will contain EMPLOYEE (notice the space in front of the word EMPLOYEE).
So before comparing , you will need to trim your value
The method i usually use, is to print out my variables when in doubt. So if you are unsure of where the problem is, you could try something like this.
(It requires you to be able to see the output, in logcat for example)
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
for(int i=0; i < myJunk.length; i++) {
System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.
if (myJunk[0].equals(val1)){
// Do Something
}
It is a bit overkill, but this is mostly to show one way of getting all the information you need to find the problem :)

Android eclipse random string array for setText?

If I understand correctly
Random ran = new Random();
String[] ButtonText = null;
Resources res = getResources();
ButtonText = res.getStringArray(R.array.ButtonText_array);
String strRandom = ButtonText[ran.nextInt(ButtonText.length)];
System.out.println("Random string is : "+strRandom);
Is a way to take my string-array items and put them in random order and now I'm wanting to setText of several buttons with individual items from the strRandom. The following is for the setText of a button
Button gm1 = (Button) findViewById(R.id.gm1);
gm1.setText();
But I dont know how to put in the strRandom items into the setText part and since I dont need it displaying what do I need to alter here.
System.out.println("Random string is : "+strRandom);
I really am not understanding the question...
If you're just asking how to set the text to a random string, do it just as you did with the println() statement,
gm1.setText(strRandom);
or
gm1.setText(ButtonText[ran.nextInt(ButtonText.length)]);
Just a side note: by convention, variables are done in camelCase, reserve AllCaps for class names. (e.g. ButtonText should be buttonText). You'll notice the SO formatter formats ButtonText as if it were a class, not an array.
gm1.setText((CharSequence)("Random string is : " + strRandom));
You need to cast from String to CharSequence

Categories

Resources