Problem
I have a button with the following XML:
<Button
android:id="@+id/firstNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="@string/firstNumber"
app:layout_constraintEnd_toStartOf="@+id/secondNumber"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Currently, the button's layout_width
is set to match_constraint
(which is the reason why it shows as "0dp," I think).
I want to make the button a square, where its width would be equal to its height. Here are the solutions that I have found so far:
Solution 1:
I could do something similar to this answer, where I would change the XML layout_width
and layout_height
values to a specific value @dimen/box_size
:
android:layout_width="@dimen/box_size"
android:layout_height="@dimen/box_size"
However, this would not be ideal as it is basically hard-coding the button width, which would not adjust well for different screen sizes (as opposed to using match_constraint
).
Solution 2:
I could write some Java code to do it (source):
public class SquareButton extends Button {
public SquareButton(Context context) {
super(context);
}
public SquareButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
}
}
This would work, but I'd rather do this within XML. Is there a way?