我有以下布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="@+id/master_table"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
</TableLayout>
</LinearLayout>
在代码中,我向表格布局添加了一些按钮,这些按钮将按行添加4个按钮:
添加按钮:
TableRow row = createTableRow();
row.addView(createToggleButton(R.id.button1, getResources().getText(R.string.button1)));
row.addView(createToggleButton(R.id.button2, getResources().getText(R.string.button2)));
row.addView(createToggleButton(R.id.button3, getResources().getText(R.string.button3)));
row.addView(createToggleButton(R.id.button4, getResources().getText(R.string.button4)));
TableLayout parent = (TableLayout)findViewById(R.id.master_table);
parent.addView(firstRow);
createToggleButton()方法的原始版本:
private ToggleButton createToggleButton(int id, CharSequence text) {
ToggleButton button = new ToggleButton(this);
button.setId(id);
button.setTextOff(text);
button.setTextOn(text);
button.setChecked(false);
button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.button, this.getTheme()));
button.setTextColor(getResources().getColorStateList(R.color.button_color));
return button;
}
这项工作,我的按钮被添加到视图中。但是当我尝试按如下方式应用LayoutParams时:
private ToggleButton createToggleButton(int id, CharSequence text) {
ToggleButton button = new ToggleButton(this);
// This line cause the button disappeared !?
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f));
button.setId(id);
button.setTextOff(text);
button.setTextOn(text);
button.setChecked(false);
button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.button, this.getTheme()));
button.setTextColor(getResources().getColorStateList(R.color.button_color));
return button;
}
即使没有发生错误,我的按钮也不再出现在视图上。这里发生了什么?
答案 0 :(得分:0)
错误应该由TableRow的宽度引起,并且它的ToggleButton子项是相互依赖的。
为TableRow设置LayoutParam
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
同时将ToggleButton的布局更改为此
button.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1.0f));