1

I want to assign a lot of TextViews in code (272 in total):

texx1 = (TextView) findViewById(R.id.resul1);
texx2 = (TextView) findViewById(R.id.resul2);
texx3 = (TextView) findViewById(R.id.resul3);
texx4 = (TextView) findViewById(R.id.resul4);
...
texx272 = (TextView) findViewById(R.id.resul272);

Any ideas on how I do this?

KristofMols
  • 3,487
  • 2
  • 38
  • 48

3 Answers3

0

The only option with using fixed ids and not having it statically typed as properties would be a list of TextView holding references to the views like this:

List<TextView> textviews = new ArrayList<>();
Resources res = getResources();

for (int i = 1; i <=272; i++) {

    int id = res.getIdentifier("resul" + i, "id", getContext().getPackageName());
    TextView tv = (TextView) findViewById(id);
    textviews.add(tv);
}

From here on you would have to access a list item in order to access the desired textview

TextView textViewToAccess = textViews.get(13);
textViewToAccess.setText(...);
ramden
  • 798
  • 1
  • 9
  • 25
0

Android has API to retrieve an id constant dynamically (by name): Android, getting resource ID from string?, it can be used to "mass-produce" these ids.
And for storing results, an array or a collection can be used.

Also, writing code that way would certainly make you an enemy of the guy who will have to maintain the code. A better idea would be to think twice, and come up with some better design.

Display Name
  • 8,022
  • 3
  • 31
  • 66
0

I'm assuming you have 272 TextViews, all with separate id's?

You can get an int id by a string like this...

public static int getIdByName(String name) {
    return getResourceIdByName(name, "id");
}

public static int getResourceIdByName(String name, String type) {
    StringBuilder s = new StringBuilder(context.getPackageName()).append(":").append(type).append("/").append(name);
    return context.getResources().getIdentifier(s.toString(), null, null);
}

So for you, you could use the above and loop around all 272 TextViews and insert into a List<TextView> like this:

List<TextView> results = new ArrayList<>();
for (int i = 1; i <= 272; i++) {
    TextView textView = (TextView) getIdByName("resul" + i);
    results.add(textView);
}
Eurig Jones
  • 8,226
  • 7
  • 52
  • 74