Skip to content

Instantly share code, notes, and snippets.

@ditn
Last active March 24, 2019 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ditn/25ff3d7059c2d4407c8043c18077eeb5 to your computer and use it in GitHub Desktop.
Save ditn/25ff3d7059c2d4407c8043c18077eeb5 to your computer and use it in GitHub Desktop.
An example of how we programmatically load fonts in Kotlin
fun loadFont(context: Context, font: CustomFont, func: (Typeface) -> Unit) {
val handlerThread = HandlerThread("fonts").apply { start() }
val handler = Handler(handlerThread.looper)
val request = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
font.query,
R.array.com_google_android_gms_fonts_certs
)
FontsContractCompat.requestFont(
context,
request,
object : FontsContractCompat.FontRequestCallback() {
override fun onTypefaceRetrieved(typeface: Typeface) {
func.invoke(typeface)
}
override fun onTypefaceRequestFailed(reason: Int) {
Timber.e("FontsContractCompat.requestFont failed with error code $reason")
}
},
handler
)
}
enum class CustomFont(val query: String) {
MONTSERRAT_REGULAR("Montserrat"),
MONTSERRAT_LIGHT("name=Montserrat&weight=300"),
MONTSERRAT_SEMI_BOLD("name=Montserrat&weight=600"),
}
@chrisvasqm
Copy link

Hey @ditn,

I have a question about this enum.

enum class CustomFont(val query: String) {

    MONTSERRAT_REGULAR("Montserrat"),
    MONTSERRAT_LIGHT("name=Montserrat&weight=300"),
    MONTSERRAT_SEMI_BOLD("name=Montserrat&weight=600"),

}

I recently ran into this video which explains the cost of enums on Android, is it outdated?

@ditn
Copy link
Author

ditn commented Mar 24, 2019

Hey @chrisvasqm, for some reason I've only just seen this message 😅

IMO it's outdated yeah, the cost of an enum is trivial. Any basic enum is turned into an int by ProGuard so it's a non-issue.

This enum is a little different because it contains a property and cannot be turned into an int or String constant. But it's a small price to pay for the increased type safety and developer productivity that enums afford. Back when everyone was supporting Gingerbread devices, perhaps allocating an extra 4 bytes per enum was a waste, but nowadays it's not worth worrying about.

Ultimately it's the wrong optimisation to be worrying about - there's an awful lot more that impacts app performance that are easier wins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment