Макет сетки. Как установить расстояние между столбцами?

Android Studio 3.1, Java 1.8, Gradle 4.1

Я использую GridLayout. Все работает нормально. Но мне нужно установить пространство (например, 10dp) между столбцами и пространством между строками. Как я могу это сделать?

main.xml:

            <GridLayout
                android:id="@+id/categoriesContainer"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:verticalSpacing="10dp"
                app:layout_constraintEnd_toEndOf="@+id/birthDateContainer"
                app:layout_constraintStart_toStartOf="@+id/birthDateContainer"
                app:layout_constraintTop_toBottomOf="@+id/birthDateContainer">


            </GridLayout>

profile_category_active.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/profileCategoryContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">       


        <TextView
            android:id="@+id/categoryNameTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginEnd="30dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="30dp"
            android:layout_marginStart="5dp"
            android:layout_marginTop="5dp"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="TextView"                />
    </android.support.constraint.ConstraintLayout>
</layout>

Действие: я добавляю строку программно:

 GridLayout gridLayout = findViewById(R.id.categoriesContainer);
    gridLayout.setColumnCount(columnCount);
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    for (int index = 0; index < 10; index++) {
     View profileCategoryActive = inflater.inflate(R.layout.profile_category_active, null, false);
            categoriesGridContainer.addView(profileCategoryActive);
            ConstraintLayout profileCategoryContainer = profileCategoryActive.findViewById(R.id.profileCategoryContainer);
            ViewGroup.LayoutParams profileCategoryContaineParams = profileCategoryContainer.getLayoutParams();
            profileCategoryContaineParams.width = (int) AndroidUtil.dpToPx(this, categoryItemWidth);
            profileCategoryContainer.setLayoutParams(profileCategoryContaineParams);
            TextView categoryNameTextView = profileCategoryActive.findViewById(R.id.categoryNameTextView);
            categoryNameTextView.setText("Ind " + profileCategoryContaineParams.width);
}

person Alex    schedule 21.12.2017    source источник


Ответы (3)


В xml GridLayout добавьте:

android:useDefaultMargins="true"

и вы получите расстояние между столбцами и строками.

person Boris Karloff    schedule 21.11.2018
comment
Получение на android:useDefaultMargins=true - person Jarin Rocks; 13.02.2019
comment
Вы можете настроить расстояние, которое это добавляет? - person Stealth Rabbi; 28.02.2020
comment
Вы не можете настроить это значение. Он устанавливается платформой. - person Sean; 10.07.2020

Вот как я этого добился, надеюсь, это кому-нибудь поможет;

<GridLayout
    android:orientation="horizontal"
    android:columnCount="3"
    android:layout_marginEnd="-10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:background="@color/colorBlack"
        android:textColor="@color/colorWhite"
        android:text="1"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:padding="15dp" />

    <TextView
        android:background="@color/colorBlack"
        android:textColor="@color/colorWhite"
        android:text="2"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:padding="15dp" />

    <TextView
        android:background="@color/colorBlack"
        android:textColor="@color/colorWhite"
        android:text="3"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:padding="15dp" />

    <TextView
        android:background="@color/colorBlack"
        android:textColor="@color/colorWhite"
        android:text="4"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:padding="15dp" />

</GridLayout>

По сути, он устанавливает поле для каждого элемента (10 dp), чтобы разместить их внутри GridLayout, а затем сдвигает GridLayout, используя отрицательное поле (-10 dp), чтобы компенсировать дополнительную ширину. Давая следующий результат;

Как отображается GridLayout

person J.C    schedule 01.04.2020

Я нашел решение:

  1. Используйте android.support.v7.widget.GridLayout
  2. Здесь программно установить поля и полный размер по горизонтали

О активность:

            View profileCategoryActive = inflater.inflate(R.layout.profile_category_active, null, false);
            categoriesGridContainer.addView(profileCategoryActive);

            // set ndroid:layout_columnWeight="1" programatically
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(
                    GridLayout.UNDEFINED, GridLayout.FILL, 1f),
                    GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f));

            params.width = (int) AndroidUtil.dpToPx(this, categoryItemWidth);
            params.bottomMargin = (int) tilePreviewLeftRightMarginDp;
            params.topMargin = (int) tilePreviewLeftRightMarginDp;
            params.rightMargin = (int) tilePreviewLeftRightMarginDp;
            params.leftMargin = (int) tilePreviewLeftRightMarginDp;
            ConstraintLayout profileCategoryContainer = profileCategoryActive.findViewById(R.id.profileCategoryContainer);
            profileCategoryContainer.setLayoutParams(params);
            TextView categoryNameTextView = profileCategoryActive.findViewById(R.id.categoryNameTextView);
            categoryNameTextView.setText("Ind " + params.width);
person Alex    schedule 21.12.2017