Android GridLayout等列宽
在Android GridLayout中,是否真的不可能轻松强制相等的列宽?尝试明显的布局Android GridLayout等列宽,android,layout,android-gridlayout,Android,Layout,Android Gridlayout,在Android GridLayout中,是否真的不可能轻松强制相等的列宽?尝试明显的布局 <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="4"
android:rowCount="8"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_gravity="center"
android:text="Button 1" />
<Button
android:id="@+id/button2"
android:layout_gravity="center"
android:text="Button 2" />
<Button
android:id="@+id/button3"
android:layout_gravity="center"
android:text="Button 3" />
<Button
android:id="@+id/button4"
android:layout_gravity="center"
android:text="Button 4" />
</GridLayout>
。。。使最右边的按钮位于明显比其他三个按钮宽的列的中心。(使用按钮文本很容易得到更糟糕的示例。)
我阅读了Android文档中关于GridLayouts中多余空间分布的内容,但很明显,在这种情况下,即使是列宽也是经常需要的(任何可能甚至是典型的),我不得不相信我遗漏了一些明显/简单的东西。使用表布局代替,并指定拉伸列
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textViewLeaveRemainingDescription"
android:stretchColumns="0,1">
<TableRow>
<Button
android:id="@+id/button1"
android:layout_gravity="center"
android:text="Button 1" />
<Button
android:id="@+id/button3"
android:layout_gravity="center"
android:text="Button 3" />
</TableRow>
<TableRow>
<Button
android:id="@+id/button2"
android:layout_gravity="center"
android:text="Button 2" />
<Button
android:id="@+id/button4"
android:layout_gravity="center"
android:text="Button 4" />
</TableRow>
</TableLayout>
只需为GridLayout的子项使用列权重:
android:layout_width="0dp"
android:layout_columnWeight="1"
记住如果项目的MinSdkimplementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:gridlayout-v7:27.1.1'
您应该使用android.support.v7.widget.GridLayout而不是GridLayout。
在使用支持库时,不要忘记使用应用程序名称空间:
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="0dp"
app:layout_columnWeight="1"
UPD:
如果以编程方式创建GridLayout,请使用GridLayout.Spec。例如:
GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(
GridLayout.spec(GridLayout.UNDEFINED, 1f),
GridLayout.spec(GridLayout.UNDEFINED, 1f)
);
layoutParams.width = 0;
yourChildView.setLayoutParams(layoutParams);
yourGridLayout.addView(yourChildView);
(对于每个子视图)尝试阅读这篇关于使用GridLayout的文章,可能会有所帮助