Adding custom number of array objects to v.findViewById(R.id.iterateHere1) without repeating code

Will :

I want to iterate 10 times adding v.findViewById(R.id.iterateHere1) without having to repeat the same syntax.

What i first had was:

SwitchCompat instance1 = v.findViewById(R.id.iterateHere1);
SwitchCompat instance2 = v.findViewById(R.id.iterateHere2);
SwitchCompat instance3 = v.findViewById(R.id.iterateHere3);

the code above was written 10 times.

I now have:

        SwitchCompat[] array = new SwitchCompat[10];

        for (int i = 0; i < 10; i++) {
            SwitchCompat instance;
            array[i] = instance = v.findViewById(R.id.iterateHere1);
            instances.add(instance);
        }

which works for each instance.

My question is how do I add 10 R.id.iterateHere1 without repeating code?

Kévin Giacomino :

You can obtain identifier of each SwitchCompat by this way :

SwitchCompat[] array = new SwitchCompat[10];

 for (int i = 0; i < 10; i++) 
      {
      SwitchCompat instance;
      String switchId = "iterateHere" + i;
      int resID = getResources().getIdentifier(switchId, "id", getActivity().getPackageName());

      array[i] = instance = v.findViewById(resID);
      instances.add(instance);
      }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11525&siteId=1