Programmatically adding TextView to Grid Layout alignment not proper

silentsudo picture silentsudo · Feb 29, 2016 · Viewed 26.6k times · Source

Hi i am trying to add TextView with drawableLeft to GridLayout. I am adding this TextView in an Loop. The TextView are getting added properly but the are not aligned properly. Each textview should take equal width in one horizontal row which is not happening.

Following is the code i am using

    GridLayout gridLayout = new GridLayout(getContext());
            gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
            gridLayout.setColumnCount(2);
            gridLayout.setRowCount(3);
            TextView titleText;
            for (int i = 0; facilities != null && i < facilities.size(); i++) {
                titleText = new TextView(getContext());
                titleText.setText(facilities.get(i));
                gridLayout.addView(titleText, i);
                titleText.setCompoundDrawablesWithIntrinsicBounds(rightIc, 0, 0, 0);
}

Answer

Mayank Bhatnagar picture Mayank Bhatnagar · Feb 29, 2016

For this you have to dynamically set the column width for the views. This will finally align each view properly with equal amount of space.

GridLayout gridLayout = new GridLayout(getContext());
            gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
            gridLayout.setColumnCount(2);
            gridLayout.setRowCount(3);
            TextView titleText;
            for (int i = 0; facilities != null && i < facilities.size(); i++) {
                titleText = new TextView(getContext());
                titleText.setText(facilities.get(i));
                gridLayout.addView(titleText, i);
                titleText.setCompoundDrawablesWithIntrinsicBounds(rightIc, 0, 0, 0);
                GridLayout.LayoutParams param =new GridLayout.LayoutParams();
                param.height = LayoutParams.WRAP_CONTENT;
                param.width = LayoutParams.WRAP_CONTENT;
                param.rightMargin = 5;
                param.topMargin = 5;
                param.setGravity(Gravity.CENTER);
                param.columnSpec = GridLayout.spec(c);
                param.rowSpec = GridLayout.spec(r);
                titleText.setLayoutParams (param);

}