gpt4 book ai didi

java - 获取动态生成的资源名称/字符串的 Drawable id

转载 作者:行者123 更新时间:2023-12-01 21:28:58 25 4
gpt4 key购买 nike

.setBackgroundResource 只能接受 int 而不是字符串,但是如果 fabrik 的每个“升级”都不会那么臃肿和丑陋的话,它看起来会好得多,所以有没有办法简化这个:

    datafab1 = getSharedPreferences("datafab1", MODE_PRIVATE);

if (datafab1.getInt("Level", 1) == 3) {
Fabrik1.setBackgroundResource(R.drawable.fablvl3);
}
if (datafab1.getInt("Level", 1) == 4) {
Fabrik1.setBackgroundResource(R.drawable.fablvl4);
}
if (datafab1.getInt("Level", 1) == 5) {
Fabrik1.setBackgroundResource(R.drawable.fablvl5);
}
if (datafab1.getInt("Level", 1) == 6) {
Fabrik1.setBackgroundResource(R.drawable.fablvl6);
}
if (datafab1.getInt("Level", 1) == 7) {
Fabrik1.setBackgroundResource(R.drawable.fablvl7);
}
if (datafab1.getInt("Level", 1) == 8) {
Fabrik1.setBackgroundResource(R.drawable.fablvl8);
}
if (datafab1.getInt("Level", 1) == 9) {
Fabrik1.setBackgroundResource(R.drawable.fablvl9);
}
if (datafab1.getInt("Level", 1) == 10) {
Fabrik1.setBackgroundResource(R.drawable.fablvl10);
}

像这样:

    datafab1 = getSharedPreferences("datafab1", MODE_PRIVATE);

String fablvl1nr = "R.drawable.fablvl"+Integer.toString(datafab1.getInt("Level", 1));
Fabrik1.setBackgroundResource(fablvl1nr);

最佳答案

您正在寻找的方法是Resource类的getIdentifier:

int i = datafab1.getInt("Level", 1);
int id= getResources().getIdentifier("fablvl"+i, "drawable", getPackageName());

关于java - 获取动态生成的资源名称/字符串的 Drawable id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37656148/

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