Yohanes AI
Yohanes AI

Reputation: 3621

Kotlin accessing asset from Fragment to set typeface

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

Answers (4)

Dimitri Hartt
Dimitri Hartt

Reputation: 1881

There is a new way to doing this:

  1. Put your_font.tff under app/src/main/res/font
  2. Create Typefaces using:
    Typeface font = ResourcesCompat.getFont(requireContext(), R.font.your_font)
    yourTextView.setTypeface(font)
  1. And to access font from XML layouts with:
    android:fontFamily="@font/your_font"

Upvotes: 2

EpicPandaForce
EpicPandaForce

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

sushildlh
sushildlh

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

Mini Chip
Mini Chip

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

Related Questions