0

I have 9 color resources in my colors.xml called colorRand01, colorRand02 .... colorRand09.

In my java code, I call

relativeLayout.setBackgroundResource(R.color.colorRand01);

to change the color.

Now I have an int variable (lets call it i) and I want to do something like:

relativeLayout.setBackgroundResource("R.color.colorRand0" + i);

Is this even possible in some way? At the moment my solution is this, but it would be great if I could make this shorter:

if(color == 1) {
            relativeLayout.setBackgroundResource(R.color.colorRand01);
        }else if (color == 2) {
            relativeLayout.setBackgroundResource(R.color.colorRand02);
        }else if (color == 3) {
            relativeLayout.setBackgroundResource(R.color.colorRand03);
        }else if (color == 4) {
            relativeLayout.setBackgroundResource(R.color.colorRand04);
        }else if (color == 5) {
            relativeLayout.setBackgroundResource(R.color.colorRand05);
        }else if (color == 6) {
            relativeLayout.setBackgroundResource(R.color.colorRand06);
        }else if (color == 7) {
            relativeLayout.setBackgroundResource(R.color.colorRand07);
        }else if (color == 8) {
            relativeLayout.setBackgroundResource(R.color.colorRand08);
        }else if (color == 9) {
            relativeLayout.setBackgroundResource(R.color.colorRand09);
}
SiebenDX
  • 3
  • 1
  • Yes it is possible abut then it should be relativeLayout.`setBackgroundResource(R.color.colorRand01 + i);` And the resource should exist of course. – blackapps Feb 18 '21 at 16:21
  • `relativeLayout.setBackgroundResource(R.color.colorRand01 + color - 1);` But you should have added the resources in that sequence. – blackapps Feb 18 '21 at 16:25
  • But maybe you better read: https://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string – blackapps Feb 18 '21 at 16:29

1 Answers1

0

Try to use this

int colorID = getResources().getIdentifier("colorRand0" + i, "color", getPackageName());
relativeLayout.setBackgroundResource(colorID);

Based on document:

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

In addition to the above note, because you don't reference resources, in build time the resources may shrink as unused resources. Your app will crash when executing this code.

beigirad
  • 4,986
  • 2
  • 29
  • 52
Shay Kin
  • 2,539
  • 3
  • 15
  • 22