Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic resource names

Tags:

java

android

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(R.id.dataTV0);
    TextView dataTV1 = (TextView) v.findViewById(R.id.dataTV1);
    TextView dataTV2 = (TextView) v.findViewById(R.id.dataTV2);
    TextView dataTV3 = (TextView) v.findViewById(R.id.dataTV3);
    TextView dataTV4 = (TextView) v.findViewById(R.id.dataTV4);
    TextView dataTV5 = (TextView) v.findViewById(R.id.dataTV5);

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

 for (int i = 0; i < 6; i++){
            (String.format("dataTV%d", i).setText(data[i]);
        }
like image 348
Alan Haden Avatar asked May 31 '26 21:05

Alan Haden


1 Answers

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)
        textView.setText(data[i]);
}

UPDATE

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)
        textView.setText(data[i]);
}
like image 178
W0rmH0le Avatar answered Jun 02 '26 11:06

W0rmH0le



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!