Clone textview to append it to a ViewGroup
Asked Answered
B

3

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.

Bushey answered 10/10, 2010 at 11:5 Comment(2)
What's the current result your getting? The myTextView is only visible once?Dumont
I have added an answer here https://mcmap.net/q/272754/-how-do-i-clone-a-view see if it works for you.Pyrogenous
D
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);
Dumont answered 10/10, 2010 at 11:44 Comment(1)
what should I do if I can't use an inflater?Arawakan
S
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");
Sancha answered 20/1, 2013 at 12:7 Comment(2)
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.Circumgyration
@ Pimp Trizkit You are right I forgot to remove it. It is old code.Sancha
C
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.

Commutative answered 23/7, 2012 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.