问题记录:Android TableLayout中动态添加TableRow不显示

在layout xml文件中定义一个TabLayout,然后在代码中动态添加数个TableRow,每个TableRow中再添加几个TextView,Button。在实现过程中发现TableRow动态添加后不能显示。

这个问题的原因是TableRow中的子控件 TextView 和 Button 在setLayoutParams时使用了LinearLayout.LayoutParams。

正确的用法应该是使用TextView/Button所在的父控件的布局参数,即TableRow.LayoutParams。

同样的,TableRow设置布局参数时应该使用所在父控件的参数TableLayout.LayoutParams。

正确的示例代码如下:

TableRow tablerow = new TableRow(getContext());
TableLayout.LayoutParams params = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
tablerow.setLayoutParams(params);

TextView week = new TextView(getContext());
TextView hour = new TextView(getContext());
Button deleteButton = new Button(getContext());
week.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,0.4f));
hour.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,0.4f));
deleteButton.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,0.2f));

week.setText("weekday");
hour.setText("12:00"+ "--" + "12:30");
deleteButton.setText("—");
deleteButton.setBackgroundResource(R.drawable.circle_style);
tablerow.addView(week);
tablerow.addView(hour);
tablerow.addView(deleteButton);
courseTime.addView(tablerow);

不在同一个地方跌倒两次。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章