0

I had this, which was working fine:

public static Integer[] photos = new Integer[]    
{R.drawable.photo1,R.drawable.photo2,R.drawable.photo3};

this.setImageResource(photos[mCellNumber]);

But I decided I wanted to put the filenames in an XML file instead, which I did, like this:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
<array name="Red">
    <item>R.drawable.photo1</item>
    <item>R.drawable.photo2</item>
    <item>R.drawable.photo3</item>
</array>
</resources>

And tried stuff like this:

String[] month = getResources().getStringArray(R.array.Red);
this.setImageResource(month[mCellNumber]);

..and..

String[] month = getResources().getStringArray(R.array.Red);
int bla = Integer.parseInt(month[mCellNumber]);
this.setImageResource(bla);

I understand why it's not working (strings/ints), but I haven't found any simple way of handling the string to integer conversion part or alternatively, using setImageResource with a string as parameter. Any suggestions?

oskare
  • 1,061
  • 13
  • 24
  • it will throw exception R.drawable.photo1 as a string is not a valid number ? – Dheeresh Singh Jun 26 '12 at 17:39
  • 1
    I've found that what you did in the first place was the best solution for me. You really can't convert "R.drawable.photo1" from a string to an int. It's really the location of an integer in your R.java file rather than a string or filename. – Frank Sposaro Jun 26 '12 at 17:39

1 Answers1

1
String[] month = getResources().getStringArray(R.array.Red);
int bla = Integer.parseInt(month[mCellNumber]);

looks it will throw exception R.drawable.photo1 as a string is not a valid number.

You an try with only saving name like photo1,photo2,photo3 and then do as below:

...

Android - Store drawable ids in a custom XML file

you can try with only saving the name like "joe_pic" and can get this way

..

   String uri = "drawable/icon";

    // int imageResource = R.drawable.icon;
    int imageResource = getResources().getIdentifier(uri, null, getPackageName());

    ImageView imageView = (ImageView) findViewById(R.id.myImageView);
    Drawable image = getResources().getDrawable(imageResource);
    imageView.setImageDrawable(image);
}

but if you have already added "R.drawable.joe_pic" complete can use String.split to get 3 rd string part

Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36