动态调整TableLayout中的按钮大小(Android)

时间:2014-02-13 04:39:31

标签: android button tablelayout tablerow layoutparams

好吧,我已经搜索了它的解决方案但无法找到它。问题很简单。 Android中有一个TableLayout,我在其中添加了几行。在Last Row中,我添加了一个按钮。现在,问题是按钮的大小不是恒定的。我的意思是,它填满了专栏。如果上面的数据需要更长的列宽,则按钮的宽度会相应增加。我也尝试了LayoutParamssetHeightsetWidth功能,但这对我没有帮助..

如果有人能帮助我,我将不胜感激。

TableLayout table=new TableLayout(this);
TableRow tableRow=new TableRow(this);
Button button=new Button(this);
TableRow.LayoutParams trParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); 
Button.setLayoutParams(trParams); 
tableRow.AddView(button); 
table.addView(tableRow);

1 个答案:

答案 0 :(得分:0)

您已在Button not按钮上调用setLayoutParams。 名称区分大小写。 Button是类,而button是您的对象。 尝试:

TableLayout table=new TableLayout(this);
TableRow tableRow=new TableRow(this);
Button button=new Button(this);
TableRow.LayoutParams trParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); 
tableRow.AddView(button, trParams); 
table.addView(tableRow);

然而,这不会解决主要问题。根据参考文档,TableRow的所有子项都被强制为MATCH_PARENT的宽度。

您可以尝试将按钮嵌套在另一个布局中。例如,将按钮放在水平LinearLayout中,然后将LinearLayout放入TableRow。