user256239 user256239 - 8 days ago 4x
Android Question

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 ways, 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=""
android:layout_gravity="right" />

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.