问题记录: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);

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值