Skip to content

Instantly share code, notes, and snippets.

@arthtilva
Created November 29, 2019 04:43
Show Gist options
  • Save arthtilva/f21bb5532bda52d1504c7971a0d14a52 to your computer and use it in GitHub Desktop.
Save arthtilva/f21bb5532bda52d1504c7971a0d14a52 to your computer and use it in GitHub Desktop.
Custom Font with attributes
package com.pay.app.controls
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Typeface
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.pay.app.R
class CTextView : AppCompatTextView {
constructor(context: Context, attrs: AttributeSet) : super(
context,
attrs
) {
applyCustomFont(context, attrs)
}
constructor(
context: Context,
attrs: AttributeSet,
defStyle: Int
) : super(context, attrs, defStyle) {
applyCustomFont(context, attrs)
}
private fun applyCustomFont(
context: Context,
attrs: AttributeSet
) {
val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.font)
val customFont = a.getString(R.styleable.font_customFont)
var tf: Typeface? = null
tf = try {
Typeface.createFromAsset(context.assets, customFont)
} catch (e: Exception) {
Typeface.createFromAsset(context.assets, "sf_pro_text_bold.ttf")
}
typeface = tf
a.recycle()
isAllCaps = false
}
companion object {
const val ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android"
}
}
==================================
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="font">
<attr name="customFont" format="string" />
</declare-styleable>
</resources>
===================================
app:customFont="@string/montserrat_semibold"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment