简体   繁体   English

Android TableLayout和水平重力

[英]Android TableLayout and horizontal gravity

I have a TableLayout that contains only one row and one cell. 我有一个TableLayout仅包含一行和一个单元格。 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 : 第一种方法,我在TableRow元素上设置了属性android:gravity =“ center_horizo​​ntal” ,它可以按预期工作:

    <?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 : 第二种方法,我直接在单元格内容(此处的按钮)上设置了属性android:layout_gravity =“ center_horizo​​ntal” ,但没有将按钮居中:

<?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. android:gravity引用视图中的子内容。 In your case, this affects the CONTENTS of the table cell. 在您的情况下,这会影响表格单元格的内容。

android:layout_gravity refers to the placement of the view in its parent. android:layout_gravity表示视图在其父级中的位置。 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 有关其他示例和更多说明,请参见此类似问题: Android上的Gravity和layout_gravity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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