Skip to content

Commit b6b895a

Browse files
committedApr 11, 2022
[Button] Fix icon textStart/End alignment with multiline text
When calculating text width to decide the icon position with textStart/End alignment, we missed accounting for multiline text. Fixes this by calculating each line's width separately and take the widest one to decide the icon position. Resolves #2007 PiperOrigin-RevId: 440982189
1 parent 05be1b9 commit b6b895a

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed
 

‎lib/java/com/google/android/material/button/MaterialButton.java

+18-3
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ private void updateIconPosition(int buttonWidth, int buttonHeight) {
568568

569569
int localIconSize = iconSize == 0 ? icon.getIntrinsicWidth() : iconSize;
570570
int availableWidth = buttonWidth
571-
- getTextWidth()
571+
- getTextLayoutWidth()
572572
- ViewCompat.getPaddingEnd(this)
573573
- localIconSize
574574
- iconPadding
@@ -612,9 +612,18 @@ private void updateIconPosition(int buttonWidth, int buttonHeight) {
612612
}
613613
}
614614

615-
private int getTextWidth() {
615+
private int getTextLayoutWidth() {
616+
int maxWidth = 0;
617+
int lineCount = getLineCount();
618+
for (int line = 0; line < lineCount; line++) {
619+
maxWidth = max(maxWidth, getTextWidth(getTextInLine(line)));
620+
}
621+
return maxWidth;
622+
}
623+
624+
private int getTextWidth(CharSequence text) {
616625
Paint textPaint = getPaint();
617-
String buttonText = getText().toString();
626+
String buttonText = text.toString();
618627
if (getTransformationMethod() != null) {
619628
// if text is transformed, add that transformation to to ensure correct calculation
620629
// of icon padding.
@@ -643,6 +652,12 @@ private int getTextHeight() {
643652
return min(bounds.height(), getLayout().getHeight());
644653
}
645654

655+
private CharSequence getTextInLine(int line) {
656+
int start = getLayout().getLineStart(line);
657+
int end = getLayout().getLineEnd(line);
658+
return getText().subSequence(start, end);
659+
}
660+
646661
private boolean isLayoutRTL() {
647662
return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
648663
}

0 commit comments

Comments
 (0)
Please sign in to comment.