1
votes

I am trying to align dynamic buttons in Grid layout.

Problem:

However, if text is more than one line the formation of buttons in row is not as needed.

String item[] = new String[]{"item1", "item2", "item3 yes", "item4","item5"};

Button[] myButton = new Button[item.length];

GridLayout scrViewButLay = (GridLayout) findViewById(R.id.grid);
    scrViewButLay.setColumnCount(4);
    scrViewButLay.setRowCount(10);

// GridLayout.LayoutParams leftMarginParams = new GridLayout.LayoutParams( // );

 for (int index = 0; index < item.length ; index++) {


        myButton[index] = new Button(this); //initialize the button here
        myButton[index].setText(item[index]);
        myButton[index].setHeight(100);
        myButton[index].setWidth(100);
        myButton[index].setTag(index);

        scrViewButLay.addView(myButton[index]);

    }
}

output image `

3
why don't you use an Adapter?Elias Fazel
i m new to android can u tell me any exampleMandeep Chaudhary

3 Answers

0
votes

I recommend to use an Adapter and then customize however you want check out this example http://androidexample.com/Custom_Grid_Layout_-_Android_Example/index.php?view=article_discription&aid=76

0
votes

I think using a recyclerView with GridLayoutManager should help you out.

This post https://inducesmile.com/android/android-gridlayoutmanager-with-recyclerview-in-material-design/ should help you out.

0
votes

You only need to apply a layout_gravity as the default seems to be to align the text to be the same height (this is why it only happens with the item 3 with two lines).

GridLayout.LayoutParams param =new GridLayout.LayoutParams();
    param.height = GridLayout.LayoutParams.WRAP_CONTENT;
    param.width = GridLayout.LayoutParams.WRAP_CONTENT;
    param.setGravity(Gravity.BOTTOM);