如何在屏幕上居中显示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在屏幕上正确。但请参阅我为相对布局中的左广告Right进行硬编码填充。由于我想支持多个scrrens,因此我希望使用以下代码将此填充作为动态。但它不起作用。
RelativeLayout gridrelativelayout = (RelativeLayout)findViewById(R.id.gridrelativelayout);
int pad=gridrelativelayout.getWidth()/3;
gridrelativelayout.setPadding(pad, 0, pad, 0);
尝试的android:layout_width = “WRAP_CONTENT” 在GridView中,同为layout_height。 – devconsole
我的问题是不同的。我上面的代码正确地对齐center.But我认为这不是很好的做法。因为我需要支持多个屏幕,如何动态设置填充。 – Ramprasad
不好意思,你可以通过编程的方式来完成它,或者你可以在dimensions.xml中定义值并像这样使用它们:'android:paddingTop =“@dimen/padding_top”'。然后为large,xlarge等提供不同版本的dimensions.xml – devconsole