Why button is not centered vertically in LinearLayout?
I have a LinearLayout, which only contains one button. I want this button to be centered vertically and aligned to the right. I tried many way开发者_高级运维s, but I couldn't make this button centered vertically. It is always aligned to the top. I also tried to put a button in RelativeLayout, the button can not be centered vertically either.
The XML is as below. Is there anything wrong with this layout? Thanks.
<?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>
Changing android:layout_gravity="right" to android:layout_gravity="right|center_vertical" didn't resolve the problem in my question.
You say in words that you want this to be centered vertically, but you have not said in XML that you want this to be centered vertically. You will need to adjust your android:layout_gravity
attribute to specify both right
and center_vertical
.
However, I would recommend you go back to RelativeLayout
. Use android:layout_centerVertical="true"
and android:layout_alignParentRight="true"
to make the button be centered vertically and right-aligned.
Also, bear in mind that your current LinearLayout
has android:layout_height="wrap_content"
, which means there is nothing to be centered inside. You need the container to have more space than its contents (e.g., fill_parent
) if you want centering to have any meaning.
This code will put the button in vertical center and on the right screen
<?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>
Try adding android:gravity="center" to your LinearLayout. I remember having read somewhere that that might do the trick.
精彩评论