【发布时间】:2018-07-31 12:16:41
【问题描述】:
我很难让wrap_content 与TableLayout 合作。这是 XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:stretchColumns="*"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:text="Column 1" />
<Button
android:id="@+id/button1"
android:text="Column 2" />
</TableRow>
</TableLayout>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2" />
</LinearLayout>
这就是它的样子:
如你所见,虽然TableLayout和Button中的layout_weight都是1,但是按钮被压到了右边。
正如here 所讨论的,我知道我可以通过将TableLayout 的layout_width 设置为0dp 来解决这个问题,但我不想这样做。我特别想将wrap_content 用作TableLayout 的layout_width,因为使用0dp 而不是wrap_content 具有我不想要的含义。
即,当使用0dp 而不是wrap_content 时,LinearLayout 将假定TableLayout 的宽度为0,然后将剩余空间分配给所有子级。然而,当使用wrap_content 时,LinearLayout 将首先计算孩子的最小宽度,从剩余空间中减去它,然后将剩余空间分配给孩子,这将导致完全不同的结果,这对我很重要具体用例。
这就是为什么我需要找到一种方法来使用wrap_content 和TableLayout。当使用LinearLayout 而不是TableLayout 时,将layout_width 设置为wrap_content 可以正常工作。只有TableLayout 似乎与wrap_content 不兼容。这是 Android 错误还是我在这里做错了什么?
【问题讨论】:
-
你到底想要什么,我不明白,你能不能看的痛。
-
我想将
wrap_content用于layout_width的TableLayout,与layout_weight的1 一起使用。问题在于LinearLayout内部的空间分配。假设LinearLayout的宽度为 1000 个单位,并且有两个孩子,layout_width设置为 0,layout_weight设置为 1。每个孩子将获得 500 个单位。现在如果两个孩子的layout_width都设置为wrap_content和layout_weight为1,Android会先从这1000个单位中减去每个孩子的最小宽度,然后分配剩余空间... -
...例如
TableLayout的宽度为200,Button的宽度为100,那么LinearLayout中将只剩下700个单元分配。TableLayout将获得额外的 350,Button也将获得额外的宽度,因此TableLayout的最终宽度将为 550,Button的最终宽度为 450。这就是将layout_width设置为wrap_content或设置为0 之间的区别。 -
好的,我明白你的意思
标签: android android-layout android-linearlayout android-tablelayout