2015-11-11 45 views
-1

这应该很简单,但我真的被卡住了。 因此,这里是我的布局:两个按钮的宽度相等,但当父母的宽度伸展到一个宽度时 - - Android

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

然后当你让按钮Visibility.GONE我需要这样的:

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

或按钮B Visibility.GONE:

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

我有尝试应有尽有。任何布局都可以做,它不一定是相对或线性或任何东西。

在此先感谢。

+0

谁能降低这个请说明一下吗?这是一个有效的问题 –

回答

3

所以,使用线性布局将每个视图的权重设置为1,方向水平。不要设置weightSum
您可以设置的知名度,走了XML或通过myView.setVisibility(View.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的。在这里,你必须设置空间和button4的可见性消失,并且设置按钮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> 
+0

你是我的英雄!为什么这个工作? –

+0

LinearLayout中具有** ** **权重的视图在它们之间平均分配空间 - 所以如果一个消失了,另一个可占据整个空间。你也可以尝试不同的权重和更多的视图,它会工作。由于没有设置weightSum,因此LinearLayout将不会“填充”View已离开的空间。 – yennsarah

+0

Ahh好吧,因为唯一的视图有1的权重,它将填充空间,但是当有n个视图的权重为n时,它就像weightSum是n一样。合理! –

相关问题