Android 如何在屏幕上居中显示GridView

Android 如何在屏幕上居中显示GridView,android,Android,如何在屏幕上居中显示GridView。我的GridView有4个项目,每行2个项目。我尝试使用相对布局中的填充将GridView居中于相对布局内。但我开发了用于多屏幕的应用程序,所以我认为硬编码填充并不是好的做法。如何在多个屏幕上居中显示此网格视图 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/too

如何在屏幕上居中显示GridView。我的GridView有4个项目,每行2个项目。我尝试使用相对布局中的填充将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>

使用android:layout\u centerInParent=“true”查看
GridView
。如果您想将最佳应用程序写入多个屏幕设备,那么这肯定有效…

,因此您需要阅读以下内容:

它对您非常有用:


应用
相对性

 android:layout_width="match_parent"
 android:layout_height="match_parent"
对于
GridView

android:layout_centerInParent = "true"
使用

android:layout\u centerHorizontal=“true”


用于GridView

请尝试GridView中的android:layout\u width=“wrap\u content”,layout\u height也是如此。我的问题是不同的。我上面的代码正确对齐中心。但我认为这不是一个好做法。因为我需要支持多个屏幕,如何动态设置填充。对不起,您可以通过编程实现,也可以在dimensions.xml中定义值并像这样使用它们:
android:paddingTop=“@dimen/padding\u top”
。然后提供不同版本的dimensions.xml用于大屏幕、xlarge等。另外,我相信您根本不需要RelativeLayout,将GridView设置为顶部布局,并在那里设置填充。这是支持多屏幕的通用文档。这个问题只针对GrdView。make android:layout\u centerInParent=“true”和gridView布局高度和布局宽度=包裹内容。它使栅格视图仅在垂直方向居中,而不是水平方向居中。我想根据屏幕缩小网格视图的宽度是的,它垂直合适。但为了水平居中,我想缩小网格视图的宽度,否则网格视图会占据整个屏幕的宽度。还可以使网格视图android:layout\u width=“match\u parent”android:layout\u height=“match\u parent”否如果将match\u parent添加到GriView,gridview与父视图(Relativelayout)匹配,因此它也不会在垂直方向上居中显示。
 android:layout_width="match_parent"
 android:layout_height="match_parent"
android:layout_centerInParent = "true"