gpt4 book ai didi

android - 另一种类型的变量和动态值

转载 作者:行者123 更新时间:2023-11-30 03:03:03 26 4
gpt4 key购买 nike

我怎样才能实现下面的代码:

    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

我如何使用动态颜色变量,例如,对于 ex R.color.green?

最佳答案

将此方法添加到您的代码中:

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());

关于android - 另一种类型的变量和动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22273011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com