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

时间:2016-06-06 11:23:32

标签: java android performance

<。> .setBackgroundResource只能接受一个int而不是一个字符串,但如果它对于fabrik的每个'levelup'来说都不会那么胖又难看,它看起来会更好,所以有没有办法简化这个:

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

2 个答案:

答案 0 :(得分:2)

您正在寻找的方法是资源类的getIdentifier

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

答案 1 :(得分:1)

使用此:

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