Search code examples
androidkotlinandroid-studiofontssystem-font

How can I programmatically retrieve the system font used on Android devices in my app?


I'm developing an Android app in Kotlin using Android Studio. How can I utilize the system fonts available on the device within my app's UI? I'm specifically looking for a way to programmatically access and apply these fonts to text elements in my app's interface. Any guidance or code examples would be greatly appreciated.

Note that I am not asking how to set a custom system font generally in Android.


Solution

  • Currently android officialy have not provided a way or any API which achieves your usecase as it might create security concerns.

    Although, here is a function which will iterate through known system font directories and checks each file in these directories, and attempts to create a Typeface object from font files with .ttf or .otf extensions.

    These are the necessary imports

    import android.graphics.Typeface
    import java.io.File
    

    Here is the function

    fun fetchSystemFonts(): List<Typeface> {
    val fontFiles = mutableListOf<Typeface>()
    
    // List of known system font directories
    val fontDirectories = listOf(
        "/system/fonts/",
        "/system/font/",
        "/data/fonts/",
        "/system/product/fonts/"
    )
    
    // Iterate through each directory
    for (directory in fontDirectories) {
        val dir = File(directory)
        if (dir.exists() && dir.isDirectory) {
            // List all files in the directory
            val files = dir.listFiles()
            files?.forEach { file ->
                // Check if the file is a font file
                if (file.isFile && (file.name.endsWith(".ttf") || file.name.endsWith(".otf"))) {
                    // Attempt to create a Typeface from the font file
                    val typeface = Typeface.createFromFile(file)
                    fontFiles.add(typeface)
                   }
               }
           }
       }
    
      return fontFiles
    }
    

    Accessing system font directories and parsing font files manually is not a typical use case for Android apps and may not work reliably across all devices and Android versions.

    This function may not retrieve all system fonts, as some font files may be stored in non-standard locations or may not be accessible due to system permissions.

    Let me know if it works for you or not. Would be happy to help furthermore.