Bou*_*ith 23 layout android 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"
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>
Run Code Online (Sandbox Code Playgroud)
...将最右边的按钮放在一个明显比其他三个更宽的列中.(使用按钮文本播放,您可以轻松获得更糟糕的示例.)
我阅读了有关GridLayouts中空间分布过多的Android文档,但看起来很明显甚至列宽也经常(任何可能甚至是典型的)在这样的情况下需要我不得不相信我遗漏了一些明显/容易的东西.
Al *_*den 25
请改用表格布局并指定拉伸列.
<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>
Run Code Online (Sandbox Code Playgroud)
kis*_*sed 15
只需为GridLayout的子项使用列权重:
android:layout_width="0dp"
android:layout_columnWeight="1"
Run Code Online (Sandbox Code Playgroud)
如果项目的MinSdk <API 21,请记住使用支持库:
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:gridlayout-v7:27.1.1'
Run Code Online (Sandbox Code Playgroud)
您应该使用android.support.v7.widget.GridLayout而不是GridLayout.使用支持库时不要忘记使用app命名空间:
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="0dp"
app:layout_columnWeight="1"
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
(对于每个儿童观点)