Font Resources
I've got this right now but I guess there would be some if on the SDK API level as compat may not be needed
/**
* @see [androidx.core.content.res.ResourcesCompat.getFont]
*/
fun Context.font(@FontRes fontRes: Int): Typeface? =
ResourcesCompat.getFont(this, fontRes)
inline fun Fragment.font(@FontRes fontRes: Int) =
context?.font(fontRes)
inline fun View.font(@FontRes fontRes: Int) =
context.font(fontRes)
I didn't take the time to think and find why ResourcesCompat.getFont would return null, as it throws if the font is not found, so maybe we could have a clear error (i.e. not !!) instead of a nullable return type.
I've added this to my extensions:
inline fun TextView.setFont(@FontRes fontRes: Int, italic: Boolean = false) {
if (!isInEditMode) {
setTypeface(font(fontRes), if (italic) Typeface.ITALIC else Typeface.NORMAL)
}
}
I'm not sure if that would be the best solution. It's perfect for me because my fonts are defined like this:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
<font
app:font="@font/montserrat_regular_normal"
app:fontStyle="normal"
app:fontWeight="400" />
<font
app:font="@font/montserrat_regular_italic"
app:fontStyle="italic"
app:fontWeight="400" />
</font-family>
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
<font
app:font="@font/montserrat_medium_normal"
app:fontStyle="normal"
app:fontWeight="500" />
<font
app:font="@font/montserrat_medium_italic"
app:fontStyle="italic"
app:fontWeight="500" />
</font-family>
So Typeface.BOLD and Typeface.BOLD_ITALIC constants are useless for me, as I would rather use a different font if I needed a bold one.
Also why did you rename the issue with 'nullability'? I'm here to propose to add this kind of extensions to the Resources split as it would be nice and is missing.
I thought I already had such extensions, when I saw you mentioning nullability, but I was wrong. I think the reason I did not add it yet is because font resources imply bigger apk size, which is something I intend to avoid, especially in libraries.
I need to explore downloadable fonts to see the state of custom fonts before deciding to commit to a public API.
If you think you're a bit knowledgeable about this fonts topic (that includes AndroidX and Play Services), feel free to comment further to help make the right decisions faster.
I'm convinced that downloadable fonts are the right thing, but I think that a library should stay realistic and implement the most commonly used patterns. The gains from such simple extensions is big compared to how little space they take, but you're right: for someone using downloadable fonts, they would be useless and take space. Should they be in a new split instead?