问题
I'm experiencing a strange issue with a TableLayout
next to a Button
. This is the 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>
And this is what I get:
This is confusing me. As you can see, both the Button
and the TableLayout
have a layout_weight
of 1. So I'd expect them to have the same width inside the LinearLayout
but for some reason, the TableLayout
takes up much more space and pushes the button all the way to the right.
How can I have the additional space available in the LinearLayout
distributed among the TableLayout
and the Button
according to the value set in layout_weight
please?
Note that I don't want to use a RelativeLayout
or ConstraintLayout
. I'm specifically looking for a LinearLayout
solution.
回答1:
Just add this to your parent. and make width 0dp
of both child
android:weightSum="2"
<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"
android:weightSum="2">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stretchColumns="*">
<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="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2" />
</LinearLayout>
回答2:
set android:layout_width="0dp"
for both Button
and TableLayout
来源:https://stackoverflow.com/questions/51611175/tablelayout-crushes-button