Reputation: 3621
I'm trying to set typeface with custom font from my assets. In java is it simple as bellow
country2TextView.setTypeface(Typeface.createFromAsset(getAssets(), "open-sans-extrabold.ttf"));
I want to access assets
from Fragment with this code bellow
country1TextView.setTypeface(Typeface.createFromAsset(context.assets, "open-sans-extrabold.ttf")`)
But I got compiler error
Only safe or non null assserted calls are allowed on a nullable receiver type of context
How to access asset from fragment? Is it good practice
if I just add safe call operator? or it is just workaround solution? What the best practice to access asset from fragment in Kotlin?
Upvotes: 0
Views: 1441
Reputation: 1881
There is a new way to doing this:
Typeface font = ResourcesCompat.getFont(requireContext(), R.font.your_font)
yourTextView.setTypeface(font)
android:fontFamily="@font/your_font"
Upvotes: 2
Reputation: 81578
Two solutions
1.)
country1TextView.setTypeface(
Typeface.createFromAsset(country1TextView.context.assets, "open-sans-extrabold.ttf")))
2.)
val Fragment.requireContext get() = context!!
country1TextView.setTypeface(
Typeface.createFromAsset(requireContext.assets, "open-sans-extrabold.ttf")))
+1.) (technically same as 1.)
fun TextView.updateTypeface(typefaceName: String) {
setTypeface(Typeface.createFromAsset(context.assets, typefaceName))
}
country1TextView.updateTypeface("open-sans-extrabold.ttf")
Please note that createTypeface
is NOT a free operation below Android 6.0, so you should create typeface once and then use that.
Upvotes: 1
Reputation: 9056
Try this
country2TextView?.typeface = Typeface.createFromAsset(context?.assets, "open-sans-extrabold.ttf")
instead of this
country2TextView.setTypeface(Typeface.createFromAsset(getAssets(), "open-sans-extrabold.ttf"));
Upvotes: 0
Reputation: 969
In Fragment always try to give context with respect to view
country1TextView.setTypeface(Typeface.createFromAsset(country1TextView.context.assets, "open-sans-extrabold.ttf")
)
or
country1TextView.typeface = Typeface.createFromAsset(country1TextView.context.assets, "open-sans-extrabold.ttf"))
`
Upvotes: 0