[Android] Fonts in XML - font family

by 민갤

Android /

XML을 사용하여 폰트 적용

Android 8.0 (API level 26) 기능

Android 4.1 (API level 16) 이상은 Support Library 26을 통해 사용할 수 있다.

1.res/font 폴더 생성

res 폴더 우클릭 > New > Android Resource Directory

New Resource Directory

Directoy name : font

Resource type : font

Source set : main

2. 폰트 파일 저장

R 파일에 컴파일 되어 R.font.fontName 또는 @font/fontName 형식으로 사용할 수 있다.

  • 확장자 : TTF, OTF
  • 리소스 파일명 : 소문자 a-z, 0-9, 밑줄(_)

3. font famliy XML 생성

font 폴더 우클릭 > New > Font resource file

File name : dico

Source set: main

Directory name : font

<?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"
    xmlns:tools="http://schemas.android.com/tools">
    <font
        android:font="@font/dico_nomal"
        android:fontStyle="normal"
        android:fontWeight="1"
        app:font="@font/dico_nomal"
        app:fontStyle="normal"
        app:fontWeight="1"
        tools:targetApi="o" />
    <font
        android:font="@font/dico_italic"
        android:fontStyle="italic"
        android:fontWeight="1"
        app:font="@font/dico_italic"
        app:fontStyle="italic"
        app:fontWeight="1"
        tools:targetApi="o" />
</font-family>

4. 사용

XML

속성 fontFamily에 xml 파일 이름을 적는다.

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/dico"/>

JAVA

Typeface typeface = getResources().getFont(R.font.dico);
tv.setTypeface(typeface);

KOTLIN

var typeface: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.dico)
tv.setTypeface(typeface, Typeface.NORMAL)

참고 Android Developer

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓