代码之家  ›  专栏  ›  技术社区  ›  user1282637

RelativeLayout中的网格视图居中

  •  0
  • user1282637  · 技术社区  · 11 年前

    我正在尝试将GridView置于RelativeLayout的中心。我将GridView的高度设置为wrap_content,RelativeLayout的重心位于中心,但GridView仍然在顶部对齐。以下是我所拥有的:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="match_parent"
        tools:context="com.example.sixerstrivia.MainActivity" >
    
        <GridView
            android:id="@+id/dashboardGrid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:columnWidth="100dp"
            android:horizontalSpacing="20dp"
            android:numColumns="2"
            android:stretchMode="columnWidth"
            android:verticalSpacing="20dp" >
        </GridView>
    
    </RelativeLayout>
    

    我该如何居中?谢谢

    3 回复  |  直到 11 年前
        1
  •  1
  •   ianhanniballake    11 年前

    而不是使用 android:gravity 在您的 RelativeLayout ,您应该使用 android:layout_centerVertical :

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.sixerstrivia.MainActivity" >
    
        <GridView
            android:id="@+id/dashboardGrid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_centerVertical="true"
            android:columnWidth="100dp"
            android:horizontalSpacing="20dp"
            android:numColumns="2"
            android:stretchMode="columnWidth"
            android:verticalSpacing="20dp" >
        </GridView>
    
    </RelativeLayout>
    
        2
  •  1
  •   Actiwitty    11 年前

    请将这些添加到GridView中: android:layout_centerVertical="true" 和 android:layout_centerHorizontal="true"

        3
  •  0
  •   yshahak    11 年前

    从RelativeLayout中移除重心。将此添加到GridView:

                android:layout_gravity="center_vertical"