Define background LinearLayout from variable String
I have a function that takes a number (in String format) as a parameter and checks if it is between the numbers from 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 as the received format is String, and the required format is Drawable, how to solve this?
1
1 answers
You can get the id
from a drawable like this:
int id = context.getResources()
.getIdentifier(fundo, "drawable", context.getPackageName());
Obtained or 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);
}
2
Author: ramaral, 2016-03-30 13:53:48