我有一个在TableRow
内动态创建TableLayout
的例程,该例程是从XML中膨胀的。我正在尝试将TableRow
s设置为特定宽度,并使用自定义按钮(ButtonElement
)填充它们......但没有任何内容显示。注销TableRow
宽度,似乎它设置为0,这可以解释为什么它没有显示。
final Drawable normalBtnBg = getResources().getDrawable(R.drawable.button_states);
TableRow tableRow;
for (int x = 0; x < xDim; x++) {
tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams(400, 20));
for (int y = 0; y < yDim; y++) {
// create the new button
mButtons[x][y] = new ButtonElement(this, x, y);
mButtons[x][y].setBackgroundDrawable(normalBtnBg);
mButtons[x][y].setLayoutParams(new LayoutParams(20, 20));
// add the button to the TableLayout
tableRow.addView(mButtons[x][y]);
}
// add the TableRow to the table
mButtonGrid.addView(tableRow, new TableLayout.LayoutParams(400, 20));
Log.d(LOG_TAG, "trWidth - " + tableRow.getWidth());
}
tableRow.getWidth()
总是返回值0 ...我已经验证了正在生成按钮,就像我将它们直接添加到mButtonGrid
一样,它们被显示(当然,不是在TableRow
,只是垂直向下)。
任何帮助表示感谢。
编辑:
想出来,请参阅下面的答案。
答案 0 :(得分:2)
仅供参考,解决了这个问题...我正在使用TableLayout.LayoutParams,但需要使用TableRow.LayoutParams才能使其工作(来自here):
final Drawable normalBtnBg = getResources().getDrawable(R.drawable.button_states);
TableRow tableRow;
for (int x = 0; x < xDim; x++) {
tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableRow.LayoutParams(400, 20));
for (int y = 0; y < yDim; y++) {
// create the new button
mButtons[x][y] = new ButtonElement(this, x, y);
mButtons[x][y].setBackgroundDrawable(normalBtnBg);
mButtons[x][y].setLayoutParams(new TableRow.LayoutParams(20, 20));
// add the button to the TableLayout
tableRow.addView(mButtons[x][y]);
}
// add the TableRow to the table
mButtonGrid.addView(tableRow, new TableLayout.LayoutParams(400, 20));
}