【发布时间】:2018-08-07 15:56:16
【问题描述】:
如何使 GridView 在屏幕上居中。我有 GridView 有 4 个项目,每行 2 个项目。我尝试使用相对布局中的填充将 GridView 居中在相对布局内。但是我为多个屏幕开发了应用程序。所以我认为硬编码填充不是一个好习惯。如何让这个 Grid 视图在多个屏幕上居中?
<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);
【问题讨论】:
-
在 GridView 中尝试 android:layout_width="wrap_content",layout_height 也一样。
-
我的问题是不同的。我上面的代码工作正常,居中对齐。但我认为这不是一个好习惯。因为我需要支持多屏幕,如何动态设置填充。
-
抱歉,您可以通过编程方式完成,或者您可以在 dimensions.xml 中定义值并像这样使用它们:
android:paddingTop="@dimen/padding_top"。然后为 large、xlarge 等提供不同版本的 dimensions.xml。 -
另外我相信你根本不需要RelativeLayout,将GridView设置为你的顶部布局并在那里设置填充。
标签: android