android - 如何使 GridView 在屏幕上居中

标签 android

如何使 GridView 在屏幕上居中。我的 GridView 有 4 个项目,每行 2 个项目。我尝试使用相对布局中的填充使 GridView 在相对布局中居中。但是我为多个屏幕开发了应用程序。所以我认为硬编码填充不是好的做法。如何在多个屏幕上将此 GridView 居中?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridrelativelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="60dp"
    android:paddingBottom="60dp"
    android:paddingLeft="150dp"
    android:paddingRight="150dp"
    tools:context=".MainMenuActivity" >

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F9F9F9"
        android:gravity="center"
        android:horizontalSpacing="50dp"
        android:numColumns="2"
        android:stretchMode="columnWidth"
        android:verticalSpacing="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

更新代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridrelativelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="150dp"
    android:paddingRight="150dp"
    tools:context=".MainMenuActivity" >

    <GridView
        android:id="@+id/gridview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:columnWidth="20dp"
        android:background="#FF0000"
        android:gravity="center"
        android:horizontalSpacing="50dp"
        android:numColumns="2"
        android:verticalSpacing="50dp"
        android:layout_centerInParent = "true" 
       />

</RelativeLayout>

此更新后的代码正确地将 gridView 居中显示在屏幕上。但是你看,我在相对布局中对左侧和右侧的填充进行了硬编码。因为我想支持多个屏幕,所以我想使用以下代码将此填充设为动态。但它不起作用。

RelativeLayout gridrelativelayout = (RelativeLayout)findViewById(R.id.gridrelativelayout);
        int pad=gridrelativelayout.getWidth()/3;
        gridrelativelayout.setPadding(pad, 0, pad, 0);

最佳答案

应用RelativeLayout

 android:layout_width="match_parent"
 android:layout_height="match_parent"

GridView

android:layout_centerInParent = "true"

关于android - 如何使 GridView 在屏幕上居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16031268/

相关文章:

java - Job Scheduler 有时不会被触发

android - 在 Android 中使用矢量图像在真实设备上出现问题。 SVG-安卓

AndroidPlot : setting the labels on the X-axis

android - onStart 调用两次,中间没有 onStop?

android - 当 AccountManager 删除帐户时,SyncAdapter 会收到通知吗?

android - 使用 ORMLite 时构造函数出错

android - 无法登录手动安装的 APK 的 Google Play 服务

android - 不需要的 textview 的位图轮廓

android - 使用 Netbeans IDE 开发 android/phonegap 应用程序是一种好方法吗?

java - ArrayOutOfIndexException 安卓