How do I center a GridView in its LinearLayout parent?
Solution 1
I don't know if you resolved your problem (i hope yes, and also i'm very late on answering on this post!), but here is a clue:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<GridView
android:id="@+id/gridview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:stretchMode="spacingWidth" >
</GridView>
</LinearLayout>
Unfortunately this work only if there is 1 content on the grid. Maybe someone can improve it!
Solution 2
android:layout_height="wrap_content"
has no meaning for widgets that have their own scrolling, likeGridView
.android:layout_alignParentTop="true"
andandroid:layout_centerInParent="true"
are forRelativeLayout
, notLinearLayout
.
Get rid of your android:layout_weight="1.0"
, change your android:layout_height
to "fill_parent"
or a specific height, change the LinearLayout
to a RelativeLayout
, and you may be in better shape.
Solution 3
set the value of LinearLayout with following attribute
android:gravity="center"
.
and remove the following line from gridview
android:layout_centerInParent="true"
Comments
-
Daniel almost 2 years
GridView is not behaving like it is supposed to. This screenshot shows that the GridView (in landscape mode) is flushed left. I want it centered.
This is the XML layout for the GridView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/templatelandscape" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <GridView android:id="@+id/commandsbarlandscape" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:layout_alignParentTop="true" android:layout_centerInParent="true" android:padding="0dp" android:verticalSpacing="2dp" android:horizontalSpacing="2dp" android:numColumns="auto_fit" android:columnWidth="52dp" android:stretchMode="spacingWidth" android:gravity="fill_horizontal" /> </LinearLayout>
What am I doing wrong ?
-
MobileEvangelist almost 12 yearsyou can also make use of RelativeLayout it's pretty good , but that doesn't matter for your problem..
-
Jenya Kirmiza over 7 yearssir what is the Common class?