Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

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

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 TextView in .java file.

This process is Too much lengthy and time consuming.

If anyone know then please help me...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Android API 16+

Beginning with Android 8.0 (API 26), there is native support for setting the fonts in XML. However, using the support library extends this down to Android 4.1 (API 16).

enter image description here

1. Add a font to your project

  • Right click the res folder and go to New > Android Resource Directory. Type font as the name and font as the Resource type.
  • Copy and paste your font into the new res/font directory. I'm just using a single font in my example, the regular dancing script font. I renamed it to dancing_script.ttf just to avoid any potential naming problems with upper case or illegal characters.

2. Create a font-family XML file.

  • Right click the res/font folder and choose New > Font Resource File. Call it whatever you want. I'm calling mine my_custom_font.xml.
  • Paste in the following code. Note that the attributes are set twice, once for android (API 26+) and once for app (API 16+).

    <?xml version="1.0" encoding="utf-8"?>
    <font-family xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
        <font
            android:fontStyle="normal"
            android:fontWeight="400"
            android:font="@font/dancing_script"
            app:fontStyle="normal"
            app:fontWeight="400"
            app:font="@font/dancing_script"
            />
    </font-family>
    

3. Set the font in XML

Now you can just use the fontFamily attribute to set the font in XML.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:fontFamily="@font/my_custom_font" />

Notes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...