Android Code Snippet [B4X] CreateB4XFont

TILogistic

Expert
Licensed User
Longtime User
Good "news", so you can download a font file and use it, at runtime.
The bad news is... why did you make me struggle when you could have published the snippet? ?
I couldn't comment before, because I was watching the football of milan vs lazio.
????
sorry.
 

Lucas Siqueira

Active Member
Licensed User
Longtime User
Small tweak for b4i.
Before trying to load the new font, it checks to see if it is added, avoiding a crash by loading the default font instead.

B4X:
Public Sub CreateB4XFont(FontFileName As String, FontSize As Float) As B4XFont
    #IF B4A
        Return xui.CreateFont(Typeface.LoadFromAssets(FontFileName), FontSize)
    #ELSE IF B4I
   
        FontFileName = FontFileName.Replace(".ttf","").Replace(".otf","")
       
        Dim existFont As Boolean = False
       
        For Each fontename As String In Font.AvailableNames
            If fontename = FontFileName Then
                existFont = True
                Exit
            End If
        Next
       
        If existFont Then
        Return xui.CreateFont(Font.CreateNew2(FontFileName, FontSize), FontSize)
        Else
            Log($"not found FontFileName: ${FontFileName}"$)
        Return xui.CreateDefaultFont(FontSize)
        End If
       
    #ELSE ' B4J
    Dim FX As JFX
    Return xui.CreateFont(FX.LoadFont(File.DirAssets, FontFileName, FontSize), FontSize)
    #END IF
End Sub


Remembering that in the b4i, it is necessary to add in the main module:
#AppFont: NameFonte.ttf
as Erel warns: https://www.b4x.com/android/forum/threads/custom-fonts.46461/


If you cannot find the correct name of the font, use this code to find out what the name of the font is, rename the file to the name found, to avoid an error in b4a with b4i: https://www.b4x.com/android/forum/threads/customfont-problem.65538/post-415157

B4X:
For Each s As String In Font.AvailableNames
 Log(s)
Next
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…