我有一个正在构建的应用程序。在其中一个子菜单中,我需要按钮的通用显示,因此我想制作一个可以显示给定数量的所需按钮的 Activity 。
我已经以编程方式成功实现了这一点,但我希望按钮的总网格填满它们所在的整个父级,这恰好是横向屏幕的 3/4。按钮的数量从 16-38 不等。!
我还成功地用其他按钮网格实现了这一点,在 xml 中,具有权重值和条目的 match_parent 值。
当我以编程方式为按钮或行分配 match_parent 值时,它会占据整个父布局,而不是像我期望的那样共享它,即使它们具有相同的权重值 1.0f
相关代码如下。我也想发布图片,但我没有这样做的声誉。
`LinearLayout layout = (LinearLayout) findViewById(R.id.linear_custom_draw); layout.setOrientation(LinearLayout.VERTICAL);
int columns = Math.min(6, 4+category); //sets number of buttons per row to 4-6
for (int i = 0; i < 4+category; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.WindowManager.LayoutParams.MATCH_PARENT,
android.view.WindowManager.LayoutParams.MATCH_PARENT)); //上面的行是填满整个线性布局的行,尽管有更多条目,这与我的 xml 定义尝试不同。 row.setOrientation(LinearLayout.HORIZONTAL); row.setWeightSum(1.0f); 如果(我%2 == 0){ row.setBackgroundColor(getResources().getColor(R.color.listview_red_backgr_color));
for (int j = 0; j < columns; j++) {
int index = (i*columns)+j;
if(formations.size() > index){
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText(formations.get(index).getName());
btnTag.setTextColor(getResources().getColor(R.color.black_overlay));
btnTag.setId(formations.get(index).getId());
row.addView(btnTag);
}
}
layout.addView(row);`
最佳答案
尝试使用TableLayout。每行将强制整个元素与具有相同权重的父元素匹配。您可以使用计数器以编程方式控制每行中的按钮数量。循环结束计数器添加您的按钮然后添加新的表格行
TableLayout tbl=new TableLayout(context);//create table
TableRow tr=new TableRow(context);//create table row
tr.addView(view);//add your button instead of the view
tbl.addView(tr);//add the row into the Table
在 XML 文件中
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/keypad"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:stretchColumns="*">
<TableRow>
<Button android:id="@+id/keypad_1" android:text="@string/_1"></Button>
<Button android:id="@+id/keypad_2" android:text="@string/_2"></Button>
<Button android:id="@+id/keypad_3" android:text="@string/_3"></Button>
</TableRow>
</TableLayout>
关于java - Android:嵌套的线性布局不会显示按钮网格,匹配父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16378806/