Clone textview to append it to a ViewGroup

2019-01-27 13:56发布

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.

3条回答
冷血范
2楼-- · 2019-01-27 14:37

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");
查看更多
姐就是有狂的资本
3楼-- · 2019-01-27 14:41

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.

查看更多
Root(大扎)
4楼-- · 2019-01-27 14:46

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);
查看更多
登录 后发表回答