Android按钮布局 - 在整个屏幕上并排显示两个按钮

JDS*_*JDS 7 xml android button android-linearlayout

我有两个按钮,我希望水平并排显示,但它们一起填充手机的水平长度.高度是包装内容,这很好.我现在的问题是只显示一个按钮(在屏幕上伸展).

这是我的XML代码:

<LinearLayout 
   android:id="@+id/page_buttons"
   android:orientation="horizontal"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:gravity="center_horizontal"

   >
   <Button
        android:id="@+id/prevButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Previous"
   /> 

   <Button
        android:id="@+id/nextButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Next"
   />
Run Code Online (Sandbox Code Playgroud)

hoo*_*d82 24

更改按钮XML以包含layout_weight属性:

<Button android:id="@+id/nextButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Next"/>
Run Code Online (Sandbox Code Playgroud)

  • 除了已接受的答案之外,我认为值得指出的是,包装两个按钮的线性布局应该具有选项 `android:orientation="horizo​​ntal"`。我很慢,一开始没有意识到这一点。 (2认同)

And*_* B. 13

既然没有人解释为什么他们的解决方案有效,我会试一试.

问题在于按钮的布局.这两个相关的属性是layout_width和layout_weight.

在其他布局系统中,当您指示布局的每个元素必须填充父级(layout_width ="fill_parent")时,它们通过在它们之间平均分配父级的空间来实现.因此,它们中的每一个都具有相同的尺寸.

相反,在Android的布局系统中,如果两个元素都有layout_width ="fill_parent",则第一个元素(在您的情况下,Previews按钮)将被拉伸以填充父级,第二个(或第三个,或等等)将没有任何元素.留下分配的空间,因此不可见.

现在,为了使其理解您希望显示两个按钮,您可以为每个按钮设置layout_weight.要使按钮具有相同的大小,请为它们设置相同的布局权重.

layout_weight定义每个按钮占用父节点的"部分"(或段)数.父母将被切割成等于儿童片段总和的多个片段.如果你想制作一个比另一个大三倍的按钮,你必须为它分配等于第一个按钮部分数量的部分数量乘以3.

因此,如果您希望"下一步"按钮比"预览"按钮大两倍,则可以执行以下操作:

  • for Previews按钮:layout_weight = 1
  • 对于下一个按钮:layout_weight = 2

因此,父母将分为3部分,其中2部分将分配给"下一步"按钮,1部分将分配给"预览"按钮.

这里采用的示例是按钮和水平布局,但这对于任何类型的对象以及垂直布局父级都可以正常工作.


小智 5

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
<Button
  android:id="@+id/button01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" 
  android:layout_below="@id/entry" 
  android:layout_alignParentLeft="true"
  android:layout_toLeftOf="@+id/space"/>
<TextView
  android:id="@+id/space"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" 
  android:layout_centerHorizontal="true"/>
<Button
  android:id="@+id/button02"
  android:layout_toRightOf="@id/button01"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_below="@id/entry" 
  android:layout_alignParentRight="true"/>  
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

好像你想要两个相同的按钮,而不是包装内容.我使用TextView创建了一个居中的间隔符,并且相对对齐.左按钮为父左侧和间隔,右按钮为左按钮,右按钮.