我们需要在Grid中放置任意控件,支持colspan(也可能在路上行进更远)。所以我看着Android's GridLayout,因为它似乎只是支持它。我已经设置了一个最小的例子,只是将TextView放在一些单元格中。
我的XML看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccccc"
android:orientation="horizontal"
android:weightSum="1"
android:id="@+id/root">
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="@android:color/holo_green_dark" android:layout_weight="1">
<TextView android:text="Erstes" android:layout_row="0" android:layout_column="0" android:layout_columnSpan="2" android:layout_columnWeight="1" android:background="#333333" />
<TextView android:text="Zweites" android:layout_row="1" android:layout_column="2" android:layout_columnWeight="1" android:background="#666666" />
<TextView android:text="Drittes" android:layout_row="1" android:layout_column="1" android:layout_columnWeight="1" android:background="#888888"/>
<TextView android:text="Viertes" android:layout_row="2" android:layout_column="3" android:layout_columnWeight="1" android:background="#aaaaaa" />
<Space android:layout_row="1" android:layout_column="0" android:layout_width="10dp" android:layout_columnWeight="1" android:layout_gravity="fill_horizontal" />
</GridLayout>
</LinearLayout>
必须放入Space
,其中有一个固定宽度,以使第二行中没有第一个单元格崩溃。我的第一个问题是,如果有另一种方法可以做到这一点?因为我想避免设置任何宽度,因为事先并不知道每个单元格的列数和相应的位置。 (编辑:我想你可以忽略android:layout_gravity="fill_horizontal"
部分。那只是我在尝试。)
同样使用该XML(或通过在代码中执行相同操作),最终结果中的列不均匀。看来,包含内容较宽(文本)的单元格的列总体上会占用更多空间。我怎么能避免这个?
您可以在下面的图片中看到结果,虽然乍一看可能几乎看不到。仅对包含10dp宽Space
视图的单元格最明显。
我在这里期待过多的GridLayout吗?谢谢你的帮助!
答案 0 :(得分:2)
对于您的第一个问题,明显的答案可能是在缺少控件的地方添加Space
视图,并将所有视图设置为具有相同的权重。
对于第二个问题,最好将layout_width
设置为0dp,因为它们默认设置为wrap_content。
在您使用API 21时忽略以下内容。
支持库有一个更好的GridLayout。它允许您为每个视图指定权重,这意味着您可以通过让每个视图具有相同的权重来均匀分配空间。
更具体地说,将compile "com.android.support:gridlayout-v7:${SUPPORT_LIBRARY}"
添加到Gradle依赖项列表中,其中$ {SUPPORT_LIBRARY}是可用的最新版本。
并使用android.support.v7.widget.GridLayout
标记进行布局。