Android Code Snippet Button Text Autosizer

Greetings,

about time I gave back to the community a little. Below is a snippet I use as a helper to size the text on my buttons, when they need to be dynamically sized. It supports a very wide range of device layouts. Let me now if you ever find it showing up strangely and we can find and tweak the problem.

Regards,
Martin

B4X:
Public Sub btnTestSizer(mBtn As Button, multipleLines As Boolean, maxSize As Int) As Int
    Dim sl As Object
    sl = mBtn.Background
 
    Dim size As Float
 
    For size = 2 To maxSize
        If btnCheckSize(mBtn, size, multipleLines) Then Exit
    Next
    size = size - 0.5
    If btnCheckSize(mBtn, size, multipleLines) Then size = size - 0.5
 
    mBtn.Background = sl
    Return size
End Sub

Private Sub btnCheckSize(mBtn As Button, size As Float, MultipleLines As Boolean) As Boolean
    Private cvs As Canvas
    Private su As StringUtils
    cvs.Initialize(mBtn)
 
    mBtn.TextSize = size
    If MultipleLines Then
        Return su.MeasureMultilineTextHeight(mBtn, mBtn.Text) > mBtn.Height*0.75
    Else
        If (cvs.MeasureStringWidth(mBtn.Text, mBtn.Typeface, size) > mBtn.Width) = True Or _
           (su.MeasureMultilineTextHeight(mBtn, mBtn.Text) > mBtn.Height*0.6) = True Then
            Return True
        Else
            Return False
        End If
    End If
End Sub

Implementation example:

B4X:
b2.Text = "Blah Blah Blah"
b2.Textsize = Utils.btnTestSizer(b2,False,30dip)
 
Last edited:
Top