I have an issue with ViewGroup.addView() method. I use this code to add new view to my layout:
TalbeLayout parent = (TableLayout)findViewById(R.id.this_does_not_matter);
parent.removeAllViews(); //this view group contains something at start
TextView tv = new TextView(this);
tv.setText("some text");
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
parent.addView(tv);
And after that I cant see my TextView. More than that, parent.getChildCount() returns correct values (1 if I try to add one child). In onClick() method of parent view I try to get width and height of TextView and all of this equals to 0. Calling requestLayout(), invalidate() and measure(500, 50) for TableView and parent has no effect. I even try to add new view with the help of view.post(Runnable), although this code is executed in UI thread.
I confused. I really don't understand what happens. Can someone explain me what I doing wrong?
One interesting moment: setLayoutParams() has no effect. If I set params with width=500 and height=50, in onClick method I get params with width=-1 and height=-1.
Code after TableRow added:
TableLayout parent = (TalleLayout)findViewById(R.id.this_does_not_matter);
parent.removeAllViews(); //this view group contains something at start
TextView tv = new TextView(this);
tv.setText("some text");
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(500, 50);
TableRow.LayoutParams tlp = new TableRow.LayoutParams(500, 50);
TableRow tr = new TableRow(this);
tr.addView(tv, tlp);
parent.addView(tr, lp);
parent.invalidate();
parent.requestLayout();
I found one more interesting thing. This Activity runs from TabHost. And "addView bug" appears only if the Activity is first selected in this TabHost. If at the first time I start Activity from another tab, all works fine.
I found solution. If switch off layout animation with android:animateLayoutChanges="false" all works fine. But I still have no idea why this happens. If anyone know reason of this behavior, it interesting for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With