Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thay đổi font chữ (Font Face) cho WebView trên Android

Giới thiệu

Ví dụ này minh họa cách sử dụng font tùy chỉnh (custom font) trong WebView bằng cách nhúng file font vào thư mục assets và khai báo trong CSS @font-face của file HTML cục bộ.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (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>

Bước 3: Tạo thư mục assets và file HTML

  1. Chuột phải vào thư mục main → New → Folder → Assets Folder.
  2. Chuột phải vào thư mục assets vừa tạo → New → File → Đặt tên webView1.html.
  3. Copy file font (ví dụ: Font.otf hoặc .ttf) vào thư mục assets.

Nội dung file webView1.html

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
    <title>WebView Custom Font</title>
    <meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>
    <style type="text/css">
        @font-face {
            font-family: 'MyCustomFont';
            src: url("file:///android_asset/Font.otf");
        }
        body {
            font-family: 'MyCustomFont', serif;
            font-size: medium;
            text-align: justify;
            color: #ffffff;
        }
    </style>
</head>
<body style="background-color:#212121">
    File này được tải từ thư mục assets của Android sử dụng WebView.
</body>
</html>

Bước 4: Code MainActivity (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        // Bật JavaScript nếu cần
        webView.getSettings().setJavaScriptEnabled(true);
        // Tải file HTML từ assets
        webView.loadUrl("file:///android_asset/webView1.html");
    }
}

Bước 5: Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. WebView sẽ hiển thị nội dung HTML với font tùy chỉnh đã nhúng.

Cách thay đổi font chữ (Font Face) cho WebView trên Android

Giải thích quan trọng

  • file:///android_asset/: Scheme đặc biệt của Android để truy cập file trong thư mục assets.
  • @font-face: Quy tắc CSS cho phép nhúng font từ file cục bộ.
  • Định dạng font: Hỗ trợ .ttf, .otf, .woff (WOFF2 có thể cần cấu hình MIME type).
  • Fallback font: Luôn khai báo font dự phòng (serif, sans-serif) sau font tùy chỉnh.

Lưu ý & Mở rộng

  • WebView không hỗ trợ font từ res/font/ (font resource của Android), chỉ dùng assets.
  • Đối với trang web từ internet (loadUrl HTTP), bạn cần inject CSS/JS để thay đổi font.
  • Kích thước file font lớn làm tăng dung lượng APK → cân nhắc subset font (chỉ giữ ký tự cần thiết).
  • API 26+ hỗ trợ FontConfig cho Downloadable Fonts, nhưng phức tạp hơn với WebView.