2

如何使 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>

更新代码:

<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);
4

4 回答 4

7

申请RelativeLayout

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

和对于GridView

android:layout_centerInParent = "true"
于 2013-04-16T08:27:23.363 回答
0

如果想将最好的应用程序写入多个屏幕设备,那么您需要阅读以下内容:

支持多屏

它对您非常有用:

支持不同的屏幕

于 2013-04-16T07:47:30.463 回答
0

用于. android:layout_centerInParent = "true"_ GridView这肯定有效...

于 2013-04-16T07:41:58.033 回答
0

利用

android:layout_centerHorizontal = "true"

对于 GridView。

于 2018-08-07T07:56:16.567 回答