2

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]);
        }
Alan Haden
  • 147
  • 14

5 Answers5

6

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]);
}
guipivoto
  • 18,327
  • 9
  • 60
  • 75
2

You should try to put those TextViews in a LinkedList:

List<TextView> tvs;
tvs = new LinkedList();
tvs.add(new TextView(this));
...

And instead of your loop you can go with:

for(TextView t : tvs){
    t.setText("text");
}
purpule
  • 116
  • 1
  • 10
1

you can achieve this by creating TextView pragmatically.

for (int i = 0; i < 6; i++){
    TextView textView = new TextView(this);
         textView.setText(data[i]);
}
Vikash Kumar Verma
  • 1,068
  • 2
  • 14
  • 30
1

i see most the answers its create TextView programmiclly, you can do it like this if you have TextView in xml layout and archive R.id in Enums :

enum drw {
  tv0(R.id.dataTV0),
  tv1(R.id.dataTV1)
  //and more

  private int drawable;
  drw(int i){
    this.drawable = i;
  }

  public int getdrawable(){
     return drawable;
  }

}

and now loop through

       Map<Integer, TextView> map = new HashMap<Integer, TextView>();

       for (drw d : drw.values()) 
          map.put(d.getdrawable(), (TextView) v.findViewById(d.getdrawable()));

       TextView myPet = dogMap.get(drw.tv0.getdrawable);
0

you would either have to use reflection to get to the textview objects by using strings. Or turn all your individual textviews into an array as well (which would make sense since they are numbered with the same name) and access them like any other array

Community
  • 1
  • 1
Gelunox
  • 772
  • 1
  • 5
  • 23