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

Динамический GridLayout

Я сделал ошибку в другом классе, поэтому она не сработала. Код ниже кажется правильным

Я пытаюсь создать динамический GridLayout. Внутри другого класса, а не этого, у меня есть метод, который проектирует строки и столбцы моего gridlayout. В приведенном ниже классе добавьте несколько кнопок в мой GridLayout:

int buttons= 6;//the number of bottons i have to put in GridLayout
int buttonsForEveryRow = 3; // buttons i can put inside every single row
int buttonsForEveryRowAlreadyAddedInTheRow =0; // count the buttons added in a single rows
int columnIndex=0; //cols index to which i add the button
int rowIndex=0; //row index to which i add the button

for(int i=0; i < buttons;i++){          
    /*if numeroBottoniPerRigaInseriti equals numeroBottoniPerRiga i have to put the other buttons in a new row*/
    if(buttonsForEveryRowAlreadyAddedInTheRow ==buttonsForEveryRow ){
        rowIndex++; //here i increase the row index
        buttonsForEveryRowAlreadyAddedInTheRow  =0;  
        columnIndex=0; 
    }   

    Spec row = GridLayout.spec(rowIndex, 1); 
    Spec colspan = GridLayout.spec(columnIndex, 1);
    GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(row, colspan);
    gridLayout.addView(button_to_add,gridLayoutParam);

    buttonsForEveryRowAlreadyAddedInTheRow ++;
    columnIndex++;

На следующем изображении вы можете видеть, что я получаю: кнопки 3 и 6 отсутствуют. Боюсь, я не правильно использую GridLayout.spec.

enter image description here

4b9b3361

Ответ 1

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

    gridLayout = (GridLayout) findViewById(R.id.gridview);

    gridLayout.removeAllViews();

    int total = 10;
    int column = 3;
    int row = total / column;
    gridLayout.setColumnCount(column);
    gridLayout.setRowCount(row + 1);
    for (int i = 0, c = 0, r = 0; i < total; i++, c++) {
        if (c == column) {
            c = 0;
            r++;
        }
        ImageView oImageView = new ImageView(this);
        oImageView.setImageResource(R.drawable.ic_launcher);            

        oImageView.setLayoutParams(new LayoutParams(100, 100));

        Spec rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
        Spec colspan = GridLayout.spec(GridLayout.UNDEFINED, 1);
        if (r == 0 && c == 0) {
            Log.e("", "spec");
            colspan = GridLayout.spec(GridLayout.UNDEFINED, 2);
            rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 2);
        }
        GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(
                rowSpan, colspan);
        gridLayout.addView(oImageView, gridParam);


    }

Ответ 2

Существуют ограничения при использовании GridLayout, следующая цитата взята из документации.

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

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

  

<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>