Sometimes, we need to get a resource from the Android resource library without knowing its name. Perhaps we have R.id.data1 through R.id.data9 and want to fetch all 9 of them without hardcoding each one.

This has been possible since API 1, through the use of getIdentifier(). I will start off by saying that this is not as efficient as referencing R, so it should be used ONLY in the event that you cannot be sure of the ID you are fetching.

The usage is actually quite easy; let's say we have nine TextViews that we want to change to the text "Foo 1" through "Foo 9". Their IDs are R.id.text1 through R.id.text9.

for (int i = 1; i <= 9; i++) {
    // This has to be called from somewhere we can access getResources() and getPackageName().
    // If we cannot access those, we need a Context, from which we can call context.getResources() and context.getPackageName().
    int myTextId = getResources().getIdentifier("text"+i, "id", getPackageName());
    TextView myText = (TextView) findViewById(myTextId);
    textInfo.setText("Foo "+i);
}

Code initially from an answer of mine on StackOverflow.

Next Post Previous Post