What is the equivalent of “android:fontFamily=”sans-serif-light" in Java code?

后端 未结 6 1806
半阙折子戏
半阙折子戏 2020-12-23 15:46

My question is quite simple:

In every of my textview, I am currently using the attribute

android:fontFamily=\"sans-serif-light\"

6条回答
  •  鱼传尺愫
    2020-12-23 16:29

    Option 1 - API 26 and higher

    // Jave
    Typeface typeface = getResources().getFont(R.font.myfont);
    textView.setTypeface(typeface);
    
    // Kotlin
    val typeface = resources.getFont(R.font.myfont)
    textView.typeface = typeface
    

    Option 2 - API 16 and higher

    // Java
    Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
    
    // Kotlin
    val typeface = ResourcesCompat.getFont(context, R.font.myfont)
    

    Check the full expiation at Android Developers Guide.

提交回复
热议问题