Skip to content

[Android] Fixed the Label Width related issues #29620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Prev Previous commit
Next Next commit
Optimize the fix to improve performace
  • Loading branch information
Ahamed-Ali committed May 29, 2025
commit c988924d442a258aa9a31e8bca7751651d115852
32 changes: 26 additions & 6 deletions src/Core/src/Platform/Android/MauiTextView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ namespace Microsoft.Maui.Platform
{
public class MauiTextView : PlatformAppCompatTextView
{
private Layout? _cachedLayout;
private string? _lastText;
private int _lastAvailableWidth;
private int _lastTotalPadding;

public MauiTextView(Context context) : base(context)
{
}
Expand All @@ -25,12 +30,27 @@ protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int availableWidth = MeasureSpec.GetSize(widthMeasureSpec);
int totalPadding = CompoundPaddingLeft + CompoundPaddingRight;
var layout = TextLayoutUtils.CreateLayout(Text, Paint, availableWidth - totalPadding, Android.Text.Layout.Alignment.AlignNormal);
int contentWidth = (int)Math.Ceiling(GetMaxLineWidth(layout));
// Calculate the required width based on the content and padding
int requiredWidth = contentWidth + totalPadding;
int desiredWidth = Math.Min(requiredWidth, availableWidth);
widthMeasureSpec = MeasureSpec.MakeMeasureSpec(desiredWidth, MeasureSpecMode.AtMost);

if (availableWidth > totalPadding)
{
// Only create new layout if text, width or padding changed
if (_lastText != Text || _lastAvailableWidth != availableWidth || _lastTotalPadding != totalPadding || _cachedLayout is null)
{
_cachedLayout = TextLayoutUtils.CreateLayout(Text, Paint, availableWidth - totalPadding, Android.Text.Layout.Alignment.AlignNormal);
_lastText = Text;
_lastAvailableWidth = availableWidth;
_lastTotalPadding = totalPadding;
}
// since the original issue 27614 occurs when the text is multiline, we only apply custom width measurement for multiline text
if (_cachedLayout.LineCount > 1)
{
int contentWidth = (int)Math.Ceiling(GetMaxLineWidth(_cachedLayout));
int requiredWidth = contentWidth + totalPadding;
int desiredWidth = Math.Min(requiredWidth, availableWidth);
widthMeasureSpec = MeasureSpec.MakeMeasureSpec(desiredWidth, MeasureSpecMode.AtMost);
}

}
}
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
}
Expand Down
Loading