Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing android:fontFamily to custom view in Android

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.

like image 434
doohickey_maker Avatar asked Dec 11 '22 00:12

doohickey_maker


2 Answers

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));
   }
like image 161
Pavel Shirokov Avatar answered Dec 26 '22 15:12

Pavel Shirokov


Use TypedArray.getResourceId to convert the font family attribute to an ID, and then use ResourcesCompat.getFont(context, fontId) to get the Typeface.

like image 39
doohickey_maker Avatar answered Dec 26 '22 15:12

doohickey_maker