我如何实现以下代码:
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
如何使用dynamiccolor变量,例如对于R.color.green?
答案 0 :(得分:1)
将此方法添加到您的代码中:
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;
}
}
然后使用它:
// Assuming that you have your color resource in colors.xml
final int dynamiccolor = getResourceID(selectedcolor, "color", getApplicationContext());
答案 1 :(得分:0)
如果你熟悉android,那么你就会知道R是一个静态类。 所以R.color.green本质上包含一个映射到colors.xml文件的int。 你可以尝试做这样的事情:
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 ));