Reputation: 104
How can i realize following code:
String dynamiccolor = "R.color." + selectedcolor;
View MainActivity = findViewById(R.id.mainactivity);
View root = MainActivity.getRootView();
root.setBackgroundColor(getResources().getColor( dynamiccolor ));
//here dynamiccolor variable is string, but for errorfree code must be INT
How can i use dynamiccolor variable like, for ex R.color.green?
Upvotes: 1
Views: 178
Reputation: 524
If you are familiar with android, then you would be knowing that R is a static class. So R.color.green essentially contains an int that maps to your colors.xml file. You can try doing something like this:
int dynamiccolor = -1;
switch(selectedcolor) {
case "green":
dynamiccolor = R.color.green;
break;
...
}
View MainActivity = findViewById(R.id.mainactivity);
View root = MainActivity.getRootView();
root.setBackgroundColor(getResources().getColor( dynamiccolor ));
Upvotes: 0
Reputation: 38098
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
Then use it so:
// Assuming that you have your color resource in colors.xml
final int dynamiccolor = getResourceID(selectedcolor, "color", getApplicationContext());
Upvotes: 1