繁体   English   中英

Android:嵌套的Linearlayouts不会显示按钮网格,与父级匹配

[英]Android: Nested Linearlayouts will not display a grid of buttons, Matching parent

我正在建设一个应用程序。 在一个子菜单中,我需要通用的按钮显示,因此我想进行一项活动,以显示给定数量的所需按钮。

我已经通过编程成功实现了此目的,但是我希望按钮的总网格能够填满放置它们的整个父对象,而这恰好是横向屏幕的3/4。 按钮的数量在16-38之间。

我还成功地通过XML中的其他按钮网格(具有权重值和条目的match_parent值)实现了这一点。

当我以编程方式分配按钮或行的match_parent值时,它占据了整个父布局,而不像我期望的那样共享它,即使它们具有相同的权重值1.0f

相关代码如下。 我也想发布图像,但是我没有声誉。

`LinearLayout布局=(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); if(i%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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM