I have a problem with the ViewGroup.addView () method. I use this code to add a new view to my layout:
TalbeLayout parent = (TableLayout)findViewById(R.id.this_does_not_matter);
parent.removeAllViews();
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 can not see my TextView. Moreover, parent.getChildCount () returns the correct values (1 if I try to add one child). In the onClick () method of the parent view, I try to get the width and height of the TextView, and all this is 0. Calling the query function Layout (), invalidate () and measure (500, 50) for the TableView and the parent has no effect. I am even trying to add a new view using view.post (Runnable), although this code is executed in the user interface thread.
I was embarrassed. I really don't understand what is going on. Can someone explain to me what I'm doing wrong?
One interesting point: setLayoutParams () has no effect. If I set the parameters with width = 500 and height = 50, in the onClick method I get params with width = -1 and height = -1.
Code after adding TableRow:
TableLayout parent = (TalleLayout)findViewById(R.id.this_does_not_matter);
parent.removeAllViews();
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 another interesting thing. This operation is performed from TabHost. And the "addView bug" only appears if Activity is selected in this TabHost first. If the first time I start Activity from another tab, everything works fine.
source
share