【问题标题】:Android laying out action bar buttonsAndroid 布局操作栏按钮
【发布时间】:2025-12-01 10:35:01
【问题描述】:

抱歉这个有点无聊的问题,但我正在尝试在“操作栏”上布置按钮,但在使用“layout_alignRight”等时遇到了麻烦。我想要达到的目标如下:

|[button1] _ _ _ 空白空间_ _ _ [button2] [button3] [button4]|

我有一个RelativeLayout,将四个按钮放在其中,我尝试了以下代码无济于事:

<RelativeLayout android:id="@+id/actionBar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#666666" >


    <Button android:id="@+id/button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignLeft="@id/actionBar"
        android:background="@drawable/buttonImg" />


    <Button android:id="@+id/button4"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignRight="@id/actionBar"
        android:background="@drawable/buttonImg" />


    <Button android:id="@+id/button3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toLeftOf="@id/button2"
        android:background="@drawable/buttonImg" />


    <Button android:id="@+id/button2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toLeftOf="@id/button3"
        android:background="@drawable/buttonImg" />                 


</RelativeLayout>

按钮似乎总是被拉长,或者全部堆积在一起。有谁知道如何实现我正在寻找的间距?

谢谢!!!

【问题讨论】:

    标签: android layout button


    【解决方案1】:

    如果只使用相对布局,你必须先锚定最左边的按钮,然后是最右边的按钮,然后添加另外两个与最右边的按钮对齐的按钮:

    <RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
        <Button android:id="@+id/b1" android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:text="Button1"></Button>
        <Button android:id="@+id/b4" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"
          android:layout_alignParentRight="true"
          android:text="Button4"></Button>
        <Button android:id="@+id/b3"
          android:layout_width="wrap_content"      
          android:layout_height="wrap_content"
          android:layout_toLeftOf="@id/b4"
          android:text="Button3"></Button>
        <Button android:id="@+id/b2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_toLeftOf="@id/b3"
          android:text="Button2"></Button>
    </RelativeLayout>
    

    【讨论】:

    • 非常感谢!我可以发誓我已经尝试过该配置...谢谢。
    • 不客气。相对布局几乎和swings spring布局一样复杂,容易迷路。