0

I'm trying to write such a code : I have a string, and if string is "stack", I want to print s.gif, t.gif, a.gif, c.gif and k.gif. Here is the code that I wrote :

    String myString = "stack";
    for(int i = 0; i < myString.length(); i++)
    {
    String source= null;
if(myString .charAt(i) == 'a')
{
    source = "R.drawable.folder.a.gif";
}
 else if (myString .charAt(i) == 'b')
{
    source = "R.drawable.folder.b.gif";
}
    ...//it goes until z
            LinearLayout linearLayout= new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.setLayoutParams(new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT,
                    AbsListView.LayoutParams.MATCH_PARENT));

            ImageView imageView = new ImageView(this);
            imageView.setImageResource();// I don't know what to write here
            imageView.setLayoutParams(new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT,
                    AbsListView.LayoutParams.WRAP_CONTENT));
            linearLayout.addView(imageView);
            setContentView(linearLayout);

}

What I'm trying to do is set source string and give it to the setImageResource(), but I failed. Can you tell me how to fix this code? Thanks.

jason
  • 6,962
  • 36
  • 117
  • 198
  • If you know the path to the resource (the `R.drawable` part) why don't you just set an `int` referencing that directly? Why are you hard-coding a String instead? – Thorn G Nov 16 '15 at 13:39
  • @TomG could you explain with an example? Thank you. – jason Nov 16 '15 at 13:41
  • 1
    Change `String source = null` to something like `int source = -1` and in your if/else blocks, set `source = R.drawable.a`. Then pass `source` to the `ImageView` as normal. – Thorn G Nov 16 '15 at 13:42
  • 1
    Side note, if you have a file `res/drawable/folder/a.gif`: Subfolders [are not supported for android resources](http://stackoverflow.com/questions/9029051/is-it-possible-to-use-sub-folders-in-drawables-in-android). Your images are probably not included in the app's resource `R` at all. – dhke Nov 16 '15 at 13:43

2 Answers2

2

First of all, Android has int-based resource pointers, so your source variable must be an int.

Then, simply assign it like this:

source = R.drawable.a

Put all your images in the res/drawable directory.

However, I am not sure if you will be able to use gifs like this without an library. Try it and if it does not work, use .pngs.

Kelevandos
  • 7,024
  • 2
  • 29
  • 46
1

Change source to int instead of String

int source;

Then use this

imageView.setImageDrawable(getResources().getDrawable(source))
Collins Abitekaniza
  • 4,496
  • 2
  • 28
  • 43