[英]How to position buttons in linear layout
我在水平 LinearLayout 中有兩個按鈕。 他們目前彼此相鄰,最左邊。 我想將第二個按鈕移動到 LinearLayout 的右端。 我在這些按鈕上嘗試了 android:gravity 但這根本沒有改變它們的位置。 謝謝
最簡單的方法是使用RelativeLayout
。 你可以在右邊給你想要的Button
屬性alignParentRight="true"
。
<Button
...
android:layout_alignParentRight="true"/>
對於水平LinearLayout
, android:layout_graivty
(這是你想要什么,而不是android:gravity
)左右不會做任何事情,因為Views
已經從右側放置到左。
如果您不確定這些, 請參閱有關android:gravity
和android:layout_gravity
之間區別的答案。
編輯
根據您需要/想什么,有可能用一個做到這一點LinearLayout
雖然可能仍然更容易和更加靈活的RelativeLayout
。 無論如何,您可以使用weight
來實現類似的目標並使用這些值。 下面給我一個Button
在左側和Button
在右邊。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Left Button"/>
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Right Button"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Right Button"/>
</LinearLayout>
您無法使用LinearLayout
實現此目的。
改用RelativeLayout
並將每個按鈕放置在相對於RelativeLayout
右側或左側。 類似於下面的例子:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentRight="true"
android:text="Button" />
</RelativeLayout>
嘗試將左側按鈕的layout_gravity
設置為left
(或start
),將右側按鈕的layout_gravity
為right
(或end
)。
問題是您目前正在使用gravity
指定對象應如何在其自身邊界內在 X 軸和 Y 軸上定位其內容。
相反,您應該使用layout_gravity
孩子提供給父母的標准重力常數。 定義子視圖在其封閉布局內的 X 軸和 Y 軸上的定位方式。
換句話說 - 您當前正在告訴按鈕如何對齊它們的子視圖,而不是告訴它們如何在其父視圖中對齊。
您可以設置android:layout_weight='1'
並且兩個按鈕將平均共享屏幕(並排),或者如果您想要它們之間的額外空間,您可以在線性布局中放置一個按鈕並設置android:layout_gravity
到left
和right
的每個。
添加一個RelativeLayout
並將值設置為layout_marginLeft
、 layout_marginTop
等。
例如。 android:layout_marginLeft="32dp" android:layout_marginTop="160dp"
使 linearLayout 方向垂直,並根據需要設置按鈕的重力 =>中心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.