两个宽度相等的按钮,但当其中一个是GONE-Android时,可以延伸到父按钮的宽度



这应该很简单,但我真的被卡住了。这是我的布局:

 __________________________
 | layout                 | 
 |[Button A ] [ Button B ]|
 |________________________|

然后当你让按钮A可见时。我需要这个:

 __________________________
 | layout                 | 
 |[      Button B        ]|
 |________________________|

或按钮B可见性。消失:

 __________________________
 | layout                 | 
 |[      Button A        ]|
 |________________________|

我已经尝试了所有。任何类型的布局都可以,它不必是相对的或线性的或任何东西。

提前谢谢。

因此,使用线性布局将每个视图的权重设置为1,方向为水平。不要设置weightSum
您可以在xml中或通过myView.setVisibility(View.GONE); 将可见性设置为gone

<LinearLayout 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:orientation="horizontal"
    tools:context="de.project.amy.amyatanim.DataFragment">

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="New Button 1" />
    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="New Button 2" />

</LinearLayout>

RelativeLayout有点棘手。在这里,您必须将空格和按钮4的可见性设置为消失,还必须将按钮5的宽度设置为与父按钮匹配,所有这些都是通过编程实现的,但并非不可能。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button4"
        android:id="@+id/button4"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/space"/>
    <View
        android:id="@+id/space"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Button5"
        android:id="@+id/button5"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/space"/>
</RelativeLayout>

最新更新