Set Linear background layout from String variable

Asked

Viewed 113 times

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 is 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 received format is String, and the required format is Drawable, how to solve this?

1 answer

2


It is possible to obtain the id of a drawable thus:

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

Obtained the id use setBackgroundResource():

fundoTopo.setBackgroundResource(id);

Everything together will be 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.