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