Подтвердить что ты не робот

Элементы центра в GridView

У меня есть GridView с 6 изображениями в 2 столбцах. Я хочу отобразить эти 6 изображений в середине экрана. Я задал свойства силы тяжести, но этот центр расположен только горизонтально. GridView отображает весь экран.

<GridView
    android:id="@+id/gridview"
    android:layout_above="@id/ad" android:layout_alignParentTop="true"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:numColumns="2"    
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"       
    android:background="#ffffff"
    android:gravity="center"
/>
4b9b3361

Ответ 1

Вот что я сделал, чтобы получить элементы в gridview в центре (обратите внимание на растяжку, ширину столбца, гравитацию и горизонтальный и вертикальный интервал):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5dp" >
    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="100dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="3"
        android:stretchMode="spacingWidthUniform"
        android:verticalSpacing="10dp" />
</LinearLayout>

Мне потребовалось некоторое время, чтобы понять это, но, столкнувшись с этими разными значениями, я смог заставить их сосредоточиться.

Ответ 2

Попробуйте обернуть GridView в LinearLayout, у которого есть дочерние элементы, и измените ваш gridview layout_height на "wrap_content". например:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_height="fill_parent"
  android:layout_width="fill_parent"
  android:gravity="center"
  android:layout_gravity="center">
    <GridView 
      android:id="@+id/homeGridView"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:numColumns="3"
      android:verticalSpacing="10dp"
      android:horizontalSpacing="10dp"
      android:stretchMode="columnWidth"
      android:gravity="center" />
</LinearLayout>

Ответ 3

Необходимо установить следующие атрибуты:

android:stretchMode="columnWidth"

... и...

android:gravity="center"

Ответ 4

Хорошо, если вы используете пользовательскую адаптивную вещь для раздувания единственного rowview внутри вашего gridview, попробуйте добавить android: gravity = "center" к макету вашего single_row.. это будет делать трюк надеемся:) то есть,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/ivClrBlock"
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        />

    <TextView
        android:id="@+id/tvClrName"
        android:layout_width="88dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:text="@string/color_name"
        android:textSize="15sp" />

</LinearLayout>

Ответ 5

Попробуйте изменить это:
android:layout_height="fill_parent"
в
android:layout_height="wrap_content"

Теперь вы сообщаете вашему виду сетки, чтобы заполнить его родительскую высоту и ширину полностью.

Ответ 6

Вот мой ответ:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/linearLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="100dip"
        android:gravity="center"
        android:numColumns="3"
        android:stretchMode="spacingWidthUniform"
        android:verticalSpacing="10dip" />
</LinearLayout>

Не используйте padding или horizontalSpacing, если он вам не нужен, так как это может вызвать проблемы с другими видами.

Обратите внимание, что fill_parent уже устарел.

Ответ 7

Я надеюсь, что это решит вашу проблему:

  <LinearLayout
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
    <GridLayout
        android:id="@+id/gridlayou4x3"
        android:rowCount="4"
        android:columnCount="3"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="80"
        android:minWidth="25px"
        android:minHeight="25px" />
  </LinearLayout>

Ответ 8

Я обнаружил, что у вас есть только gridlayout обертывание содержимого на height и width.

android:layout_centerHorizontal="true"

Он будет центрировать себя для размера, который ему нужен, но если у вас есть его соответствие родительскому. Вы технически центрируете его, основываясь на множестве родительского пустого пространства, компенсирующего ваших детей.

Ответ 9

Проблема возникла, когда я обновил адаптер gridview:

        gridView = inflater.inflate(R.layout.mobile, null);

to

        gridView = inflater.inflate(R.layout.mobile, parent, false);

поэтому я просто отменил обратный вызов, используя попытку catch, если старая (нулевая) версия не удалась.