Skip to content

Commit

Permalink
[Button] Fix icon textStart/End alignment with multiline text
Browse files Browse the repository at this point in the history
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
  • Loading branch information
drchen committed Apr 11, 2022
1 parent 05be1b9 commit b6b895a
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/java/com/google/android/material/button/MaterialButton.java
Expand Up @@ -568,7 +568,7 @@ private void updateIconPosition(int buttonWidth, int buttonHeight) {

int localIconSize = iconSize == 0 ? icon.getIntrinsicWidth() : iconSize;
int availableWidth = buttonWidth
- getTextWidth()
- getTextLayoutWidth()
- ViewCompat.getPaddingEnd(this)
- localIconSize
- iconPadding
Expand Down Expand Up @@ -612,9 +612,18 @@ private void updateIconPosition(int buttonWidth, int buttonHeight) {
}
}

private int getTextWidth() {
private int getTextLayoutWidth() {
int maxWidth = 0;
int lineCount = getLineCount();
for (int line = 0; line < lineCount; line++) {
maxWidth = max(maxWidth, getTextWidth(getTextInLine(line)));
}
return maxWidth;
}

private int getTextWidth(CharSequence text) {
Paint textPaint = getPaint();
String buttonText = getText().toString();
String buttonText = text.toString();
if (getTransformationMethod() != null) {
// if text is transformed, add that transformation to to ensure correct calculation
// of icon padding.
Expand Down Expand Up @@ -643,6 +652,12 @@ private int getTextHeight() {
return min(bounds.height(), getLayout().getHeight());
}

private CharSequence getTextInLine(int line) {
int start = getLayout().getLineStart(line);
int end = getLayout().getLineEnd(line);
return getText().subSequence(start, end);
}

private boolean isLayoutRTL() {
return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
}
Expand Down

0 comments on commit b6b895a

Please sign in to comment.