简体   繁体   中英

Android TableLayout and horizontal gravity

I have a TableLayout that contains only one row and one cell. I would like the content of my cell to be horizontally centered. I tried two approaches :

First method, I set the attribute android:gravity="center_horizontal" on the TableRow element and it works as expected :

    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TableRow android:gravity="center_horizontal">
            <Button
                android:id="@+id/MyButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"            
                android:text="@string/Hello" />
        </TableRow>
    </TableLayout>

Second method, I set the attribute android:layout_gravity="center_horizontal" directly on the cell content (the button here) but that doesn't centers the button :

<?xml version="1.0" encoding="utf-8"?>
        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <TableRow>
                <Button
                    android:id="@+id/MyButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"            
                    android:layout_gravity="center_horizontal"
                    android:text="@string/Hello" />
            </TableRow>
        </TableLayout>

Can someone explain me why the second approach doesn't work ?

Thank you

Riana

android:gravity refers to the child content inside the view. In your case, this affects the CONTENTS of the table cell.

android:layout_gravity refers to the placement of the view in its parent. In this case, the placement of the cell in the table, but NOT the cell contents. The cell contents will NOT be affected.

See this similar question for some other examples and further explanation: Gravity and layout_gravity on Android

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM