Alan Haden Alan Haden - 1 year ago 101
Android Question

Dynamic resource names

I would like to populate a number of TextViews through a for loop.
This isn't an actual code sample but I hope it's enough to give you an idea of what I'm trying to do.
I'm not even sure this is possible but I'm hoping someone has found a way.

TextView dataTV0 = (TextView) v.findViewById(;
TextView dataTV1 = (TextView) v.findViewById(;
TextView dataTV2 = (TextView) v.findViewById(;
TextView dataTV3 = (TextView) v.findViewById(;
TextView dataTV4 = (TextView) v.findViewById(;
TextView dataTV5 = (TextView) v.findViewById(;

String[] data; //This is acquired from another source

for (int i = 0; i < 6; i++){
(String.format("dataTV%d", i).setText(data[i]);

Answer Source

I think one option is Resources.getIdentifier()

for (int i = 0; i < 6; i++){
    TextView textView = (TextView) findViewById( getResources().getIdentifier(String.format("dataTV%d", i), "id", getPackageName() ) )
    if(textView != null)


To avoid to many funcions calls:

TextView textView;
Resources rresources = getResources();
String packageName = getPackageName();

for (int i = 0; i < 6; i++){
    textView = (TextView) findViewById( resources.getIdentifier(String.format("dataTV%d", i), "id", packageName ) )
    if(textView != null)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download