Mr. Pivirotto
Mr. Pivirotto

Reputation: 281

Displaying image based on string chosen?

I have a code rite now that just generates a random drink combination from an array, what I need to do is have a different image assigned to each choice and have it display that image. Here is my code for a random drink:

    if(Vodka.equals(true)){
                final TextView text2 = (TextView) findViewById(R.id.display2);
                randomIndex = random.nextInt(array_city.Vodka.length);
                text2.setText(array_city.Vodka[randomIndex]);
            }

Say this code spits out "Smirnof" then i display a picture of the bottle, it spits out "Sky" then changes to a picture of that bottle. How would i do this without making an if statement for each option, my arrays are very long and that would be alot of if statements i was just Hoping that there is an easier way to do it? Thanks anybody for your help! it is very much appreciated I have been stuck on this for a while.

=============================================================== @Joan

Here is what i am trying to put together using your code:

    //Run option Vodka
            if(Vodka.equals(true)){
                final TextView text2 = (TextView) findViewById(R.id.display2);
                randomIndex = random.nextInt(array_city.Vodka.length);
                text2.setText(array_city.Vodka[randomIndex]);

                final ImageView image = (ImageView) findViewById(R.id.imageView1);
                int Cimage = getResources().getIdentifier(array_city.Vodka[randomIndex], null, "com.famousmods.what.should.i.drink");
                image.setImageResource(Cimage);
            }

Here is what my array looks like (a smaller example):

    public static final String[] Vodka = {"Absolut Vodka","Finlandia","Ketel One","Polmos Krakow","Skyy","smirnoff vodka",
    "Stolichnaya","Fleischmann's","Gilbey's","Gordon's","Wolfschmitt","Five-O-Clock"};

I have put the file "smirnoff_vodka.png" into my res/drawables as an example but it doesnt work?

Upvotes: 0

Views: 288

Answers (1)

Joan
Joan

Reputation: 143

You can use getResources().getIdentifier("image_name", null, "your_application_package"); on your context to retrieve the image id. Then you can use this id as you would use R.id.image_name.

EDIT: It needs to be "drawable" instead of null. See below.

Upvotes: 2

Related Questions