Skip to content

Android Quick Tip: Read and use installed fonts

At the moment, Xojo Android Framework does not yet provide support for System.FontCount/System.FontAt. However, if you still want to get an overview of all fonts available in the system, we can do this with a few lines of Xojo code.

Usually TTF fonts are used in Android, so the following code will only search for these. Fonts that are globally accessible are located in the /system/fonts/ folder in Android. Using the FolderItem.Children Iterator, we can search for these and generate a visual representation of all fonts in an AndroidMobileTable.

Create a new Android project. Add an AndroidMobileTable (Table1) to Screen1 and lock the control on all four sides of Screen1. Do the same with a Label (Label1) above Table1. Then add the Opening event to Table1 and insert the following code:

Const fontSuffix = ".ttf"

Var folder As FolderItem = New FolderItem("/system/fonts/")
Var counter As Integer

' Iterate over all files within the folder
For Each item As FolderItem In folder.Children

  ' Check for font file (ttf)
  If Not item.Name.EndsWith(fontSuffix) Then Continue

  counter = counter + 1
  ' Create a new Picture for visual representation of the font
  Var pic As New Picture(Me.Width, 50)
  Var g As Graphics = pic.Graphics

  ' Draw font name to the picture
  g.Font = New Font(item, 20)
  g.DrawText(item.Name.Left(item.Name.Length - 4), 5, pic.Height / 2 - g.TextHeight / 2 + g.Font.Ascent)

  Me.AddRow("")

  ' Save Font as RowTag
  Me.RowTagAt(Me.LastAddedRowIndex) = g.Font

  ' Add RowPicture to the row
  Me.RowPictureAt(Me.LastAddedRowIndex, False, 0) = pic
Next

Self.Title = Self.Title + " (" + counter.ToString + ")

Now add the SelectionChanged event to Table1 with the following code:

' Change Label1 font to the selected one 
Label1.TextFont = Me.RowTagAt(Me.SelectedRowIndex)

Now run the project and you will have a complete font selection dialog in your Android app.

The code can be optimized by using the path to the font file as the RowTagAt instead of a Font object and the Font object is only created and assigned in the Table1.SelectionChanged event.

The example project runs from Xojo 2023r4.

Happy Coding.

Martin T. is a Xojo MVP and has been very involved in testing Android support.