Как программно установить столбец Вес карты - PullRequest
1 голос
/ 18 июня 2019

Я использую GridLayout, который изначально содержит 3 cardviews.Теперь, когда пользователь нажимает последнюю карту, я хочу добавить еще одну карту к GridLayout.

Но в начальных 3 карточках, которые я создал в xml файле, содержится атрибут 'columnweight'.Поэтому я хочу установить этот атрибут для вновь созданного cardview после onClick.

Я видел некоторые вопросы, связанные с этим.Но они создают gridlayout также программно и не хотят создавать gridLayout программно.Как я могу это сделать?

Примечание: - Каждая моя структура CradView выглядит следующим образом: - Cardview-> LinearLayout-> TextView

Я прошел по ссылке ниже this

Но, как я уже сказал, они создали gridLayout программно, и я хочу это сделать.

Мое начальное расположение с GridView, связанное с 3 cardViews, равно

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:id="@+id/activity_manager"
        android:weightSum="10">

        <Space
            android:layout_height="30dp"
            android:layout_width="wrap_content"/>

        <GridLayout
            android:id="@+id/mainGrid"
            android:columnCount="2"
            android:alignmentMode="alignMargins"
            android:columnOrderPreserved="false"
            android:layout_weight="5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="14dp" >

            <android.support.v7.widget.CardView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardElevation="8dp"
                android:layout_marginRight="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginBottom="16dp"
                app:cardCornerRadius="8dp"
                android:padding="0dp">

                <LinearLayout
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_margin="4dp"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:text="Mumbai Hackathon"
                        android:textAlignment="center"
                        android:layout_marginTop="6dp"
                        android:textColor="@color/colorPrimary"
                        android:textSize="18sp"
                        android:textStyle="bold"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardElevation="8dp"
                android:layout_marginRight="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginBottom="16dp"
                app:cardCornerRadius="8dp"
                android:padding="0dp">

                <LinearLayout
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_margin="4dp"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:text="Game of Codes (GOC)"
                        android:layout_marginTop="6dp"
                        android:textAlignment="center"
                        android:textColor="@color/colorPrimary"
                        android:textSize="18sp"
                        android:textStyle="bold"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:id="@+id/add_file"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardElevation="8dp"
                android:layout_marginRight="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginBottom="16dp"
                app:cardCornerRadius="8dp">

                <LinearLayout
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_margin="4dp"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:text="+\nAdd New File"
                        android:layout_marginTop="6dp"
                        android:textAlignment="center"
                        android:textColor="@color/colorPrimary"
                        android:textSize="18sp"
                        android:textStyle="bold"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

        </GridLayout>
    </LinearLayout>
</ScrollView>

1 Ответ

0 голосов
/ 18 июня 2019

Источник: GridLayout (не GridView), как равномерно растянуть все дочерние элементы

ОБНОВЛЕНИЕ : веса поддерживаются с API 21.См. Ответ PaulT для получения более подробной информации. END UPDATE Существуют ограничения при использовании GridLayout, следующая цитата взята из документации .

"GridLayout не обеспечивает поддержку принципавес, как определено в весе. В общем, поэтому невозможно настроить GridLayout для распределения избыточного пространства в нетривиальных пропорциях между несколькими строками или столбцами ... Для полного контроля над распределением избыточного пространства в строке или столбце; используйтеподпредставление LinearLayout для хранения компонентов в связанной группе ячеек. "

Вот небольшой пример, который использует подпредставления LinearLayout.(Я использовал Space View, который занимает неиспользуемую область и перемещает кнопки в нужное положение.)

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="1"
>
    <TextView
        android:text="2x2 button grid"
        android:textSize="32dip"
        android:layout_gravity="center_horizontal" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="Button 2" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
    >
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="Button 4" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</GridLayout>
...