이 튜토리얼에서는 Kotlin을 사용하여 Android 앱에서 WebView의 글꼴(font face)을 변경하는 방법을 단계별로 알아봅니다. 커스텀 폰트 파일을 assets 폴더에 추가하고, HTML과 CSS의 @font-face 규칙을 활용해 WebView에 적용하는 과정을 다룹니다.
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
예제 코드
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>3단계: assets 폴더 및 HTML 파일 생성
프로젝트에 assets 폴더를 생성합니다. 그런 다음 assets 폴더를 마우스 오른쪽 버튼으로 클릭하여 새 파일(webView.html)을 만들고 아래 코드를 작성합니다.
여기서 핵심은 CSS의 @font-face 규칙입니다. file:///android_asset/Font.otf 경로를 통해 assets 폴더에 저장된 폰트 파일을 불러와 body 요소에 적용합니다.
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>WebView9</title>
<meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>
<style type="text/css">
@font-face {
font-family: 'Font';
src:url("file:///android_asset/Font.otf")
}
body {
font-family: 'Font', serif;
font-size: medium;
text-align: justify;
color:#ffffff
}
</style>
</head>
<body style="background-color:#212121">
All our dreams can come true, if we have the courage to pursue them.” – Walt Disney.
</body>
</html>4단계: MainActivity.kt 작성
src/MainActivity.kt 파일에 아래 코드를 추가합니다. WebView를 찾아 assets 폴더에 있는 HTML 파일을 로드하는 것이 전부입니다.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val webView: WebView = findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/webView.html");
}
}5단계: AndroidManifest.xml 확인
androidManifest.xml 파일에 아래 코드가 올바르게 설정되어 있는지 확인합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행하기
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바에서 Run 아이콘
을 클릭합니다. 실행 옵션에서 본인의 모바일 기기를 선택하면, 기기 화면에 커스텀 글꼴이 적용된 WebView가 표시되는 것을 확인할 수 있습니다.
