How do you pass a font family inside the res/font
folder, e.g. @font/roboto_medium
, as an attribute to a custom view in Android in XML, and then read it inside the custom view into a Typeface
object? This is necessary to do custom graphical rendering of the text.
For example:
<MyCustomView android:fontFamily="@font/roboto_medium"/>
Then inside MyCustomView.kt:
override fun onCreateView(...) {
// parse android:fontFamily attribute into Typeface object
val typeface: Typeface = ???
}
None of the Typeface
functions seems to support this. One of them accepts a custom font inside the assets
folder, and another accepts a resource font integer directly embedded inside the Java/Kotlin code e.g. R.font.roboto_medium
.
The answer of doohickey_maker really works.
In layout.xml you need to add android:fontFamily="@font/name"
In attrs.xml
<declare-styleable name="LoadingButton">
<attr name="android:fontFamily" />
In CustomView
int fontFamilyId = typedArray.getResourceId(R.styleable.LoadingButton_android_fontFamily, 0);
if (fontFamilyId > 0) {
mButton.setTypeface(ResourcesCompat.getFont(getContext(), fontFamilyId));
}
Use TypedArray.getResourceId
to convert the font family attribute to an ID, and then use ResourcesCompat.getFont(context, fontId)
to get the Typeface
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With