Android Question auto fit text

merlin2049er

Well-Known Member
Licensed User
Longtime User
Is there a way to auto size or auto fix text to a button. I've got a names on buttons, and if it wraps, it doesn't appear on the button.

I guess I can resize my buttons.
 

KMatle

Expert
Licensed User
Longtime User
Take this code. Works good for me:

B4X:
Sub SetButtonTextSize(ex As Button, txt As String)
   
    Log(">> This is going to change:" & ex)
   
    Dim dt As Float
    Dim limit = 0.5 As Float
    Dim h As Int
    Dim stu As StringUtils
   
    ex.Text = txt
    ex.TextSize = 72
    dt = ex.TextSize
    h = stu.MeasureMultilineTextHeight(ex, txt)   
    Do While dt > limit OR h > ex.Height
        dt = dt / 2
        h = stu.MeasureMultilineTextHeight(ex, txt)   
        If h > ex.Height Then
            ex.TextSize = ex.TextSize - dt
        Else
            ex.TextSize = ex.TextSize + dt
        End If
    Loop
    ex.TextSize=ex.textsize *0.8

End Sub

Call it with

B4X:
SetButtonTextSize(Btn,Btn.Text)

The following libraries must be checked: StringUtils and Java Object.

You can change 0.8 (=80%) to a value you need.

Important: The button layout must be set before calling the sub.

It works with labels and edittexts, too (copy the sub, rename it and change "ex as button" to "ex as label or edittext"
 
Upvote 0
Top