Define background LinearLayout from String Variable

1

I have a function that takes a number (in the String format) as a parameter and checks if it is between the numbers 1 to 5. Here's the function:

if (fundo.equals("1") || fundo.equals("2") || fundo.equals("3") || fundo.equals("4") || fundo.equals("5"))
{
    fundo = "bg_" + fundo;
    fundoTopo.setBackground(R.drawable. <-- Queria colocar a variavel aqui);
}

But this generates an error because the format received is String, and the required format is Drawable, how to solve this?

    
asked by anonymous 30.03.2016 / 15:38

1 answer

2

You can get id of a drawable like this:

int id = context.getResources()
                .getIdentifier(fundo, "drawable", context.getPackageName());  

Get id use setBackgroundResource () :

fundoTopo.setBackgroundResource(id);

All together will look like this:

if (fundo.equals("1") || fundo.equals("2") || fundo.equals("3") || fundo.equals("4") || fundo.equals("5"))
{
    fundo = "bg_" + fundo;
    int id = context.getResources()
                    .getIdentifier(fundo, "drawable", context.getPackageName()); 
    fundoTopo.setBackgroundResource(id);
}
    
30.03.2016 / 15:53