Создание элементов GridView квадратными - PullRequest
77 голосов
/ 02 июля 2011

Я бы хотел, чтобы элементы моего GridView были квадратными.Имеется 2 столбца, а ширина элементов равна fill_parent (например, они занимают как можно больше горизонтального пространства. Элементы представляют собой пользовательские виды.

Как сделать высоту элементов равной их переменной ширине?

Ответы [ 12 ]

1 голос
/ 30 августа 2011

В соответствии с ответом @ Gregory, мне пришлось обернуть изображение в LinearLayout, чтобы GridView не мог манипулировать его размерами с квадрата. Обратите внимание, что внешний LinearLayout должен быть настроен так, чтобы иметь размер изображения, а ширина столбца GridView должна быть шириной изображения плюс любое поле. Например:

    <!-- LinearLayout wrapper necessary to wrap image button in order to keep square;
    otherwise, the grid view distorts it into rectangle.

    also, margin top and right allows the indicator overlay to extend top and right.

    NB: grid width is set in filter_icon_page.xml, and must correspond to size + margin
    -->
<LinearLayout
        android:id="@+id/sport_icon_lay"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:orientation="vertical"

        android:layout_marginRight="6dp"
        android:layout_marginTop="6dp"
        >

    <ImageButton
            android:id="@+id/sport_icon"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:maxHeight="60dp"
            android:maxWidth="60dp"
            android:scaleType="fitCenter"
            />
</LinearLayout>

и GridView, как:

   <GridView
        android:id="@+id/grid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"

        android:columnWidth="66dp"

        android:numColumns="auto_fit"
        android:verticalSpacing="25dp"
        android:horizontalSpacing="24dp"
        android:stretchMode="spacingWidth"

        />
0 голосов
/ 02 января 2014

В вашей деятельности

 DisplayMetrics displaymetrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
 valX = displaymetrics.widthPixels/columns_number;

в пользовательском адаптере GridView

 v.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, YourActivity.valX));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...