Search code examples
kotlinandroid-jetpack-composeandroid-resourceskotlin-multiplatformcompose-multiplatform

Can't use a font in Kotlin Multiplatform


Pretty simple; just created a Compose Multiplatform project from the wizard.

Went ahead and created the Theme; but I wanted to use the same font so I put poppins.ttf inside commonMain/resources/font/.

Then I declared the following in commonMain module:

expect val projectFontFamily: FontFamily

On the commonDesktop module I used:

actual val projectFontFamily: FontFamily = FontFamily(
  Font("font/poppins.ttf")
)

Great, that worked. Now on commonAndroid:

actual val projectFontFamily: FontFamily = FontFamily(
  Font(R.font.poppins)
)

For some reason the R class is not properly being generated and I cannot use R.font.poppins.

If I rename "resources" to "res" and shove the font into res/font/ then it works. (But I just duplicated the font file).

How do I get around doing this?


Solution

  • It turns out it's rather a gradle issue and some inexperience with KMM.

    Kotlin multiplatform projects by default (regardless of the platform) provide their resources in a folder called resources inside each module.

    Problem is that the default folder for Android needs to be called res

    So you can apply a fix either way:

    Change resources folders to res and modify gradle accordingly or indicate in the Android project that the resource folder is not res but resources.

    We ended up doing the latter in our project

    // build.gradle.kts
    android {
      ...
      sourceSets["main"].res.srcDirs(
        "src/commonMain/resources",
        "src/androidMain/resources"
      )
      ...
    }