How to set custom font in .xml file instead of .java file?

前端 未结 8 502
無奈伤痛
無奈伤痛 2020-12-05 10:14

I am creating one Application in which I want to set custom font.

But I can\'t use custom Fonts in .xml file, for using this I need to initialize each and every Text

8条回答
  •  半阙折子戏
    2020-12-05 10:38

    As other answers suggest, you may use a font downloaded from google: Android Api 16+

    open the textAppearance spinner in the designer: Choose a font for your View (Tap More Fonts...) like so:


    In the dialog choose your custom font and download it to your project:

    Now, you can refer to this font from xml using the fontFamily attribute:

        

    As a bonus, you can also use it from code: see snippet:

    Toast toast = Toast.makeText(this, yourString, Toast.LENGTH_SHORT);
    LinearLayout layout = (LinearLayout) toast.getView();
    TextView tvToast = (TextView) layout.getChildAt(0);
    
    //Here is the relevant part:
    Typeface typeface = ResourcesCompat.getFont(this, R.font.aclonica);
    tvToast.setTypeface(typeface);
    toast.show();
    

提交回复
热议问题