I have a LinearLayout
with horizontal orientation that contains 8 MaterialButton
s with a single digit as the text for each button.
The button has styling:
<com.google.android.material.button.MaterialButton
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/cellButton"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="5dp"
android:padding="0dp"
android:insetTop="0dp"
android:insetBottom="0dp"
android:insetLeft="0dp"
android:insetRight="0dp"
android:clickable="true"
android:focusable="true"
android:textColor="@color/foreground"
android:textSize="20sp"
android:gravity="center"
android:textAlignment="gravity"
app:strokeWidth="2dp"
app:elevation="0dp"
app:cornerRadius="7dp"
/>
and the text starts centred as expected.
On the press of a button the final two buttons have their visibility set to GONE
, leaving only 6 buttons in the row. These buttons no longer have centred text (it is shifted to the left, as if still using the original offset even though the buttons have grown):
The same thing happens but in reverse (text is off-centre to the right) if I start with 6 buttons in a row and add two more (but the newly-added ones on the end are correct.
The text still becomes off-centre when I:
TextView
s rather than buttonsGONE
buttons to have a weight of 0removeView
on the horizontal LinearLayout
to remove the hidden buttons rather than just changing their visibilityI have tried resetting the gravity of the buttons when they are clicked (the '2' on the second line was a grey button that was clicked, causing it to have its text/colour set, and the gravity to have been updated to Gravity.CENTER | Gravity.BOTTOM
), and calling requestLayout
on the vertically aligned LinearLayout
containing each row after the appropriate buttons have been hidden, but neither of these had any effect.
Apologies all, it turned out that the problem was that I was using a custom button (Set button height equal to the button width) which messed with the measuring process:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(width, width);
}
Removing this overload solves the issue.