2013-01-06 79 views
0

我想使2按钮占据屏幕宽度的一半,但是我真的只有一个按钮来到屏幕上,并采取全屏幕宽度。我想要所有的分辨率,所以不想修改宽度。一个按钮将左半等将右半这可怎么办android简单布局

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:gravity="center"> 


     <Button 
      android:id="@+id/button1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_gravity="left" /> 


     <Button 
      android:id="@+id/button2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_gravity="right" /> 

    </LinearLayout> 

</ScrollView> 
+0

此问题已在stackoverflow上被询问了几次 - 一个示例:http://stackoverflow.com/questions/11286147/android-setting-button-width-half-the-screen/11286169#11286169 - 如果您使用你会发现更多的搜索 –

回答

2

使用以下布局技术。使用Linear Layout。将layout_width分配给0dip。将layout_weight分配给每个按钮1,以便它们占用等于总宽度。如果你希望他们占据一半屏幕的高度,而不是宽的,在上面XML layout_widthlayout_height之间改变布局的orientationvertical和交换价值:为每一个按钮的layout_heightmatch_parent

<LinearLayout 
     android:id="@+id/LinearLayout1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="horizontal"> 

     <Button 
      android:id="@+id/ButtonLeft" 
      android:layout_width="0dip" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:text="ButtonLeft" 
      /> 
     <Button 
      android:id="@+id/ButtonRight" 
      android:layout_width="0dip" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:text="ButtonRight" 
      /> 

    </LinearLayout> 

PS。

关于layout_weight

layout_weight决定父元素空间是如何划分之间它的孩子。如果你想在你的按钮之间按1:4的宽度进行分割,那么你可以将layout_weight的1个按钮分配给“1”,另一个按钮分配给“3” - > 1 /(1 + 3)= 1/4 。 layout_weight又是如何工作的 - 高度还是宽度? layout_weight从免费或未使用的空间分发。在上述布局中,我们将0dip分配给按钮的宽度。因此,根据layout_weight,父项的水平空间或宽度未使用或空闲,并在您的按钮之间分配。希望这可以帮助。

+0

完美它解决了这个问题,但我不明白的布局重量属性,你可以给我有用的指导呢? –

+0

我已更新我的答案,以包含'layout_weight'的概念 –

3

可以定义layout_weight定义视图的大小。使用layout_width0dp是使用重量设置(根据lint)的最佳方式。当两个按钮具有相同的值时,两者都使用50%的宽度。玩弄这些价值观以获得这种感觉。

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:text="Button" 
     android:layout_weight="1"/> 

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

</LinearLayout> 
+0

完美它解决了这个问题,但我不明白的布局权重属性,你能给我有用的指导呢? –

+1

有很多[问题](http://stackoverflow.com/questions/3995825/what-does-androidlayout-weight-mean)和答案。只需使用搜索。 – WarrenFaith