[英]Why button is not centered vertically in LinearLayout?
我有一個LinearLayout,它只包含一個按鈕。 我希望此按鈕垂直居中並與右側對齊。 我嘗試了很多方法,但我無法使這個按鈕垂直居中。 它始終與頂部對齊。 我也嘗試在RelativeLayout中放一個按鈕,按鈕也不能垂直居中。
XML如下。 這個布局有什么問題嗎? 謝謝。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#E8E3E4">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="More"
android:layout_gravity="right" />
</LinearLayout>
將android:layout_gravity =“right”更改為android:layout_gravity =“right | center_vertical”並未在我的問題中解決問題。
你用文字說你希望它垂直居中,但是你沒有在XML中說過你希望它垂直居中。 您需要調整android:layout_gravity
屬性以指定right
和center_vertical
。
但是,我建議你回到RelativeLayout
。 使用android:layout_centerVertical="true"
和android:layout_alignParentRight="true"
使按鈕垂直居中並右對齊。
另外,請記住,您當前的LinearLayout
具有android:layout_height="wrap_content"
,這意味着內部沒有任何內容。 如果您希望居中具有任何意義,則需要容器具有比其內容更多的空間(例如, fill_parent
)。
此代碼將按鈕放在垂直中心和右側屏幕上
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_vertical">
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Click Me" />
</LinearLayout>
嘗試將android:gravity =“center”添加到LinearLayout。 我記得在某個地方讀過那可能有用的伎倆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.