13

I have a ViewGroup defined in XML with a view inside, at onCreate time I'd like to have a variable of those.
I don't want to go through the hassle of using a listview+adapter cause its clearly overkill as I know the list won't change since onCreate()
This is more or less the code I'd like to have.

TextView mytextview = myViewGroup.findViewById(R.id.mytext);

for(String test : strings){
  mytextview = mytextview.clone();
  mytextview.setText(test);
  myViewGroup.addView(mytextview);
}

But it is not working.

Arkaitz Jimenez
  • 22,500
  • 11
  • 75
  • 105

3 Answers3

19

Maybe use an inflater, and put the textview in an external layout file:

View v = LayoutInflater.from(this).inflate(R.layout.textview_include, null);
viewGroup.addView(v);
Mathias Conradt
  • 28,420
  • 21
  • 138
  • 192
2

Using code of Mathias Lin and using the hint from javahead76:

LinearLayout x = (LinearLayout) findViewById(R.id.container); 

    for (int i = 0; i < 5; i++) {
        View c = LayoutInflater.from(this).inflate(R.layout.singlerow, x);  
        TextView t = ((TextView)findViewById(R.id.textView1));
        t.setId(i+10000);
        t.setText("text"+i);            
    }
    TextView b = (TextView) findViewById(10003);
    b.setText("10003");
Khaled Annajar
  • 15,542
  • 5
  • 34
  • 45
  • 1
    Whats the purpose of the `findViewById` at the end of the `for` loop? That function returns the `View` for id `0` to `4` (in your case), but your not using that anywhere. – Pimp Trizkit Jan 27 '13 at 06:20
  • @ Pimp Trizkit You are right I forgot to remove it. It is old code. – Khaled Annajar Jan 28 '13 at 07:35
1

If you do this, you will most likely get the exact same id for every view created this way. This means doing things like ((TextView)v).setText("some text"); will be called on every TextView previously inflated from the same layout. You can still do it this way, but you should call setId() and have some reasonable method for ensuring you do not get the same id twice in a row - incrementation or universal time, etc.

Also, I think Android reserves a certain range of id's for dynamically created id's. You might avoid ID's in this range; but honestly, I don't know the id system works so I could be wrong on this point.

Bikram Kumar
  • 393
  • 1
  • 4
  • 15
javahead76
  • 1,050
  • 10
  • 11