I've looked through numerous similar questions here at SO, but nothing helps. I have a hierarchy of different nested layouts, all have android:layout_width="fill_parent"
, and the inner-most layout has android:layout_width="wrap_content
- I need to align it at the center (horizontally). How do I do that?
Update:: I've found the cause of the problem - if I put the inner LinearLayout into RelativeLayout with android:layout_width="fill_parent"
, it still wraps it's content. The TableRow, however, is really filling the 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" > <FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableRow > <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="1" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="2" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> </TableRow> </TableLayout> </FrameLayout> </LinearLayout>
To center align LinearLayout, assign android:gravity attribute of this LinearLayout with the value “center”. Let us create an Android application with LinearLayout containing two Button widgets as children. We shall center align these children using gravity attribute.
Try layout_gravity and gravity attributes in the LinearLayout to make all the childs to be centered by default. This above is a splash screen activity. So there are two childs - ImageView and TextView. Both are center aligned.
When using the RelativeLayout , you can use android:layout_centerInParent="true" , which will do what it says, center it inside its parent.
If in linearlayout your orientation vertical, you can put the textview in the "horizontal center" by android:layout_gravity="center" . For centering textview vertically you need to set layout_height of textview to match_parent and set android:gravity to "center".
These two attributes are commonly confused:
android:gravity
sets the gravity of the content of the View it's used on. android:layout_gravity
sets the gravity of the View or Layout relative to its parent.So either put android:gravity="center"
on the parent or android:layout_gravity="center"
on the LinearLayout itself.
I have caught myself a number of times mixing them up and wondering why things weren't centering properly...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With