Reputation: 7691
For a specific feature I needed to implement a custom TextView
which would use spannables to style text. Everything works, except the font used by the custom view seems to be the default font rather than the one I'm specifying. Reducing to the minimal code triggering the problem I created this class:
class DummyTextViewBad : TextView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
}
In my xml, just changing the widget from TextView
to DummyTextViewBad
makes the font (avenir) go away and render using the system default. However, if I set the font manually like this, it works:
class DummyTextViewGood : TextView {
constructor(context: Context?) : super(context) {
setAvenir(context)
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
setAvenir(context)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
setAvenir(context)
}
fun setAvenir(context: Context?) {
try {
typeface = ResourcesCompat.getFont(context!!, R.font.avenir_font)
} catch (e: Exception) {
println("Failed to set font");
}
}
}
Why do I need to set the font manually even when my subclass doesn't do anything else at all? Am I missing some needed super()
calls to configure the font? If the font issue is known, what is the standard way to extract the font from the xml attributes and avoid hardcoding it in code?
Upvotes: 1
Views: 355
Reputation: 101
You need extend of AppCompatTextView because by default in XML import AppCompatTextView but if make a new components you need import AppCompatTextView not TextView ;)
Upvotes: 6
Reputation: 3711
why we need create a custom view just for using font family, TextView already support this.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/avenir_font"/>
Upvotes: 0