首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android LinearLayout 按鈕對齊:RelativeLayout 容器配合 alignParentLeft/Right

     編輯:程式設計綜合問答

問題

水平 LinearLayout 中兩個按鈕,左邊一個靠左,右邊一個靠右,中間空白。

解決:改用 RelativeLayout

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp">

    <Button
        android:id="@+id/eyesback"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true" />

    <Button
        android:id="@+id/eyesforward"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true" />

</RelativeLayout>

LinearLayout 替代方案

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">

    <Button
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:gravity="left" />

    <Button
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:gravity="right" />

</LinearLayout>

利用 weightSum 和 layout_weight 平均分配空間,按鈕內部 gravity 控制靠左/右。

建議

  • 簡單左右對齊用 RelativeLayout 最直觀
  • 需平均分配空間用 LinearLayout + weight
  • 現代佈局首選 ConstraintLayout,app:layout_constraintStart_toStartOf="parent" / End_toEndOf
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved