Clone textview to append it to a ViewGroup

前端 未结 3 1096
心在旅途
心在旅途 2020-12-20 12:29

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+

相关标签:
3条回答
  • 2020-12-20 12:51

    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");
    
    0 讨论(0)
  • 2020-12-20 12:53

    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.

    0 讨论(0)
  • 2020-12-20 13:08

    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);
    
    0 讨论(0)
提交回复
热议问题