GridLayout (not GridView) how to stretch all children evenly

后端 未结 20 2182
独厮守ぢ
独厮守ぢ 2020-11-22 09:35

I want to have a 2x2 grid with a buttons inside. This is only ICS so I am trying to use the new GridLayout given.

Here\'s the XML of my layout:

 <         


        
20条回答
  •  故里飘歌
    2020-11-22 10:14

    You can make this lot faster by overriding ViewGroup onLayout method. This is my universal solution:

    package your.app.package;
    
    import android.content.Context;
    import android.view.ViewGroup;
    
    public class GridLayout extends ViewGroup {
    
        public GridLayout(Context context) {
            super(context);
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int columns = 2;//edit this if you need different grid
            final int rows = 2;
    
            int children = getChildCount();
            if (children != columns * rows)
                throw new IllegalStateException("GridLayout must have " + columns * rows + " children");
    
            int width = getWidth();
            int height = getHeight();
    
    
            int viewWidth = width / columns;
            int viewHeight = height / rows;
    
            int rowIndex = 0;
            int columnIndex = 0;
    
            for (int i = 0; i < children; i++) {
                getChildAt(i).layout(viewWidth * columnIndex, viewHeight * rowIndex, viewWidth * columnIndex + viewWidth, viewHeight * rowIndex + viewHeight);
                columnIndex++;
                if (columnIndex == columns) {
                    columnIndex = 0;
                    rowIndex++;
                }
            }
        }
    
    }
    

    EDIT: Don't forget match_parent for children!

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    

提交回复
热议问题