I am trying to reach GridLayoutwith square children, as you can see from this image.

Thus, basically the view should be adjusted depending on the number of elements without declaring the column size and row size. Is this possible for GridLayout? If not, then forget about this question.
Now let's move on to the square part. I tried to implement this code
public class SquareLinearLayout extends LinearLayout {
public SquareLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSize == 0 && heightSize == 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int minSize = Math.min(getMeasuredWidth(), getMeasuredHeight());
setMeasuredDimension(minSize, minSize);
return;
}
final int size;
if (widthSize == 0 || heightSize == 0) {
size = Math.max(widthSize, heightSize);
} else {
size = Math.min(widthSize, heightSize);
}
final int newMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(newMeasureSpec, newMeasureSpec);
}
}
although it makes a square of the child layout, it also takes up the entire width of the screen, pushing other children out of the visible part of the layout.
Do you have any links or do you have code similar to this class but not taking up the full width of the layout? Thanks in advance.