I recommend a different approach, using the gravity="center_horizontal" parent layout layout, and the next step is to create a custom view that extends the ImageButton class to set its size to square, it's really simple.
So create a new class, name it SquareImageButton and continue with ImageButton . add a default constructor with context and attributes and let it call a superfunction, you don't need to add anything.
Now override the onMeasure() method (which gives the measured width and height in int values), take the minimum value and (as needed) call setMeasuredDimension(w, h) with the new minimum value so that it is square. This worked for me, and here is the code if you are a little lost:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int minDimension = Math.min(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(minDimension, minDimension); }
source share