什么是最好的Android布局

时间:2013-09-19 23:19:31

标签: android android-layout android-xml

我使用了RelativeLayout和Linearlayout来实现这一目标。(在图片中)!enter image description here

  1. 使用相对布局,我将按钮定位为固定宽度,并使用marginLeft和marginRight。问题是,如果设备有更大的屏幕,左,右边距不会扩大太多,按钮宽度也是固定的。

     <RelativeLayout>
    
        <!-- Row1 -->
    
    <Button1
      alignParentTop = "true" 
      marginLeft = "5dip"
      marginRight="5dip"
     width="80dip"/>
    
    <button2
     alignParentTop ="true"
     center="@id/Button1"
     marginLeft = "5dip"
     marginRight="5dip"
     width="80dip" />
    
    <button2
     alignParentRight="true"
     marginLeft = "5dip"
     marginRight="5dip"
     width="80dip"/>
    
    
    <!-- Row2 -->
    
    <Button3
      below="button1"
      marginLeft = "5dip"
      marginRight="5dip"
     width="80dip"/>
    
    <Button4
      below="button2"
      marginLeft = "5dip"
      marginRight="5dip"
     width="80dip"/>
    
        </RelativeLayout>
    
  2. 使用RelativeLayout parent,使用按钮创建2个水平linearlayout。现在按钮的宽度为0dip,重量为1.但是,我无法创建第二行。

  3. <RelativeLayout> <linearLayout orientation="horizontal"> <!-- Row1 --> <Button1 width="0dip" weight="1"/> <button2 width="0dip" weight="1"/> <button2 width="0dip" weight="1"/> </linearLayout> <!--Row2--> <linearLayout orientation="horizontal"> Couldn't using this approach </linearLayout> </RelativeLayout>

4 个答案:

答案 0 :(得分:2)

您当然可以像其他人所建议的那样使用TableLayoutGridLayout,但如果您想修改LinearLayout解决方案,只需稍加更改即可实现此目的。像这样:

<LinearLayout android:orientation="vertical">   
   <!-- Row1 -->
   <LinearLayout android:orientation="horizontal">
     <Button    
     android:layout_width="0dip"
     android:layout_weight="1"/>

    <Button
     android:layout_width="0dip"
     android:layout_weight="1"/>

    <Button
     android:layout_width="0dip"
     android:layout_weight="1"/>
   </LinearLayout>

  <!-- Row2 -->
  <LinearLayout android:orientation="horizontal" android:weightSum="3">    
     <Button    
     android:layout_width="0dip"
     android:layout_weight="1"/>

    <Button
     android:layout_width="0dip"
     android:layout_weight="1"/>
  </LinearLayout>
</LinearLayout>

请注意,第二行的weightSum最多可加3,但每个按钮的重量仅为1。

答案 1 :(得分:0)

我会选择Gridlayout来实现此功能。主要代码更少,更好地处理方向更改。

答案 2 :(得分:0)

如果我理解正确,你想伸出按钮来填写屏幕。请尝试使用TableLayout。一个例子是here。基本上,您为表按钮使用表行和列,并指定stretchColumns“以确保您的列(以及因此按钮)伸展以填充空间。

答案 3 :(得分:0)

正如@prijupaul所说,你可以使用Gridlayout,但我会坚持使用LinearLayout。我不知道你为什么把所有东西都包装在RelativeLayout中,我想你可以避免这种情况。

<linearLayout  orientation="vertical">   
   <LinearLayout orientation="horizontal">
     <!-- Row1 -->
     <Button1     
     width="0dip"
     weight="1"/>

    <button2
     width="0dip"
     weight="1"/>

    <button2
     width="0dip"
     weight="1"/>
   </LinearLayout>

  <!-- Row2 -->
  <LinearLayout orientation="horizontal">    
     <Button1     
     width="0dip"
     weight="1"/>

    <button2
     width="0dip"
     weight="2"/>
</LinearLayout>
相关问题