Android:如何在 TableLayout 的列中居中 View ?

标签 android tablelayout

我正在尝试创建一个带有复选框网格的 TabeLayout。顶部是 2 个标题,每增加一行都包含一个标签和 2 个复选框。我希望表格填满所有可用空间,第一列向左,复选框及其标题在列中居中。在下面的布局中,标题显示正确居中,但复选框不是。我为其中一个 CheckBox 添加了背景颜色,这表明 CheckBox 实际上增长以填充其列(这就是它不会按需要居中的原因);尽管有“wrap_content”布局参数。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:orientation="vertical">
    <TableLayout 
        android:stretchColumns="1,2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TableRow>
            <TextView 
                android:text="" 
                android:gravity="center_horizontal"
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content">
            </TextView>
            <TextView 
                android:text="First category" 
                android:gravity="center_horizontal"
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content">
            </TextView>
            <TextView 
                android:text="2nd category" 
                android:gravity="center_horizontal"
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content">
            </TextView>
        </TableRow>
        <TableRow>
            <TextView 
                android:text="Row 1: " 
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content">
            </TextView>
            <CheckBox
                android:background="#FF001122"
                android:layout_height="50dip"
                android:layout_width="wrap_content" 
                android:gravity="center_horizontal">
            </CheckBox>
            <CheckBox
                android:layout_height="50dip"
                android:layout_width="wrap_content" 
                android:gravity="center_horizontal">
            </CheckBox>
        </TableRow>
    </TableLayout>
</LinearLayout>

enter image description here

最佳答案

在 CheckBox 上,您不想设置 android:gravity="center_horizo​​ntal",而是设置 android:layout_gravity="center_horizo​​ntal"

android:gravity 控制 View 如何在其自己的容器内布置其内容,并且由于您将宽度设置为 "wrap_content",因此没有空白空间让 CheckBox 将其自身居中。

android:layout_weight 告诉父 View (在本例中为 TableRow)如何定位 subview ,因此它会将 CheckBox 在表格单元格内居中。

关于Android:如何在 TableLayout 的列中居中 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5515174/

相关文章:

java - AndEngine setRotationCenter 移动旋转的物体

android - Android TableLayout/TableRow 的 iOS/Swift 编程等效项

html - 有没有办法截断(隐藏)宽表格单元格?

html - 嵌套表中的 Colspan 样式失败

css - 如何制作可在 Outlook 中使用的填充框?

android - 通话结束后返回应用

android - ListView不可点击,行中的所有小部件都是TextView

android - onSuccess 方法未在 android 中的 firebase 中调用

android - python可以构建android应用程序吗?

android - 在 TableLayout 中对齐列