Search code examples
androidandroid-studiogrid-layoutandroid-gridlayout

GridLayout matches parent by resizing the last column and row only (AndroidStudio)


I have a GridLayout of 4 columns and 5 rows. If set to wrap_content for layout_width and layout_height, all cells are of equal size, as they should be. When I set it to match_parent, however, all cells except those in the last row and column stay the same size, with the last row increasing dramatically in height to fill the rest of the vertical space and the last column increasing in width to fill the rest of the horizontal space. That is, most cells don't resize at all, and row 5 and column 4 become hugely distorted.

wrap_content: enter image description here

match_parent: enter image description here

How can I have GridLayout keep all cells the same size when it matches parent?


Solution

  • If you have static number of rows and columns, you can override cell view's method onMeasure this way (if you want to fill, for example, whole display):

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      int width = getResources().getDisplayMetrics().widthPixels / COLUMN_COUNT;
      int height = getResources().getDisplayMetrics().heightPixels / ROW_COUNT;
      setMeasuredDimension(width, height);
    }