Dynamically choosing drawable - android

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

Related

Creating resource reference ints programmatically

I am building a quiz app with questions in a string resource, as well as an answer. They are formatted by numbers like so:
<string name="ques1">What color is the sky?</string>
<string name="ques2">What sound does a cow make?</string>
The answers are also strings corresponding to the same number as the questions:
<string name="ans1">Blue</string>
<string name="ans2">Moo</string>
I have created a QA class for holding both a question and the answer, as well as the user's response from an EditText. At the "loading" of my app these classes are created and filled by reading from the strings resource.
I can programmatically enter these no problem, it is a lot of copy pasting but it will get the job done:
QA.setQuestion(getString(R.string.ques1));
QA.setAnswer(getString(R.string.ans1));
quizList.add(QA);
QA.setQuestion(getString(R.string.ques2));
QA.setAnswer(getString(R.string.ans2));
quizList.add(QA);
etc...
The problem is that I want to be able to add questions and answers to the xml at any time without having to add yet another repetition of the above method. What I want to do is essentially this:
String refBase = "R.string."
String ans = "ans";
String ques = "ques";
int numOfQues = 25; //only change when questions are added or removed
for (int i = 0; i < numOfQues; i++)
{
String referenceQ = refBase + ques + i;
String referenceA = refBase + ans + i;
QA.setQuestion(getString(referenceQ));
QA.setAnswer(getString(referenceA));
quizList.add(QA);
}
I cannot cast a string to an int like this obviously, but I am wondering if there is a way to implement a reference "builder", where I don't have to repeat many lines of code just to read another string with the same name but incremented number.
I understand that I can also just create an array.xml with one for questions and one for answers, making sure their position in each array corresponds. This would be easiest I think, but I guess I am wondering if it is possible to create references to string values through the code like my example?
You can use this method to get the question or answer String by its resource name:
String getQAString(boolean isQuestion, int index) {
String prefix = isQuestion? "ques" : "ans";
int resId = getResources().getIdentifier(prefix + index, "string", getPackageName());
return resId != 0? getString(resId) : "";
}
The loop to add questions and answers (assume they start from 1 and end at 25):
int numOfQues = 25;
for (int i = 1; i <= numOfQues; i++) {
String referenceQ = getQAString(true, i);
String referenceA = getQAString(false, i);
QA.setQuestion(referenceQ);
QA.setAnswer(referenceA);
quizList.add(QA);
}

Can you convert String version of R.id to int?

As an exercise, I am building a calendar. Below is a small segment of my code. I have a class MyCalendar that extends Activity.
This Activity will be linked to an XML file whose layout includes seven TextViews with ids R.id.day0 thru R.id.day6.
If converted from String to int, will the Activity's findViewById() method recognize the int version of these ids?
String Days [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
TextView dayViews [];
private void populateViews (){
for (int counter = 0; counter < Days.length; counter++){
int ID = Integer.parseInt("R.id.day"+counter);
dayViews [counter] = (TextView) findViewById(ID);
dayViews[counter].setText(Days[counter]);
}
I have not tried it myself. but this answer https://stackoverflow.com/a/11595723/1514861 suggest you can do it like this:
private String getStringResourceByName(String aString) {
String packageName = getPackageName();
int resId = getResources().getIdentifier(aString, "string", packageName);
return getString(resId);
}
EDIT: I think you would also need to replace "string" with "id"
Definitely not.
R class from Java are ids generated at compilation.
I would do:
final int[] days = { R.id.day0, R.id.day1, ... };
for (int day : days) {
// ...
}
NO, int ID = Integer.parseInt("R.id.day"+counter);, what you did in there is making a representation of String to Integer, not an actual mapping from R class to xml resource.
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(), like our friends said. For that, you'll need to call it inside a loop, inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:
Your resources file:
R.string.string0
R.string.string1
R.string.string2
...
R.string.string9
In java:
for (i=0;i<10;i++){
int resourceId = getResources().getIdentifier("string"+i, "string", this.getPackageName())
println(getResources().getString(resourceId));
}
Then, in your rescourceId variable, you'll have an equivalent to: R.string.string0 to R.string.string9. And, in println, you'll have the value correspondent of your resources string.
In Kotlin:
for (i in 0..10){
val resourceId = this.resources.getIdentifier("string"+i, "string", this.packageName)
println(resources.getString(resourceId))
}
With the same explanation that I said before.

How to select a drawable image by matching a string value to the image name?

I have an arraylist of strings, I need to randomly select an index and if the string value was
"bear", then set background of button to bear.jpg.
OK, my research shows that resources are accessed by an int id, not their name, I am not sure the best way to achieve what I want to do. Here is my code:
list.add("alligator");
list.add("bear");
list.add("beaver");
list.add("bison");
randomInt = randomGenerator.nextInt(list.size());
b1.setBackgroundResource(R.drawable.list.get(randomInt));
Now of course the last line of the code is wrong, I wrote it to show what I want to achieve. My latest attempt to accomplish this was trying to get the resource id and access the resource this way, but I don't know if this is the way to do this, and if it is I am not using the correct code. I am trying hard to do this by myself but I could use some advice on what to do here. Here is my attempt:
String mDrawableName = "bear";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
String s= Integer.toString(resID);
Use the below code
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
b1.setBackgroundResource(resID);
Try this:
list.add("alligator");
list.add("bear");
list.add("beaver");
list.add("bison");
randomInt = randomGenerator.nextInt(list.size());
int resourceId = getResources().getIdentifier(list.get(randomInt), "drawable", getPackageName());
b1.setBackgroundResource(resourceId);

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

Categories

Resources