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

Cách đặt font chữ tùy chỉnh cho Button trong Android

Hướng dẫn này trình bày cách thay đổi font chữ (typeface) cho Button trong Android lập trình. Android hỗ trợ sẵn các font hệ thống (sans, serif, monospace) và cho phép load font tùy chỉnh từ file .ttf hoặc .otf trong thư mục assets/fonts/.

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

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Layout (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/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnChangeFont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Nhấn để đổi font Button này" />

    <Button
        android:id="@+id/btnChangeFont2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@id/btnChangeFont"
        android:layout_marginTop="10dp"
        android:text="Nhấn để đổi font Button này" />

</RelativeLayout>

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

import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button btnChangeFont, btnChangeFont2;

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

        btnChangeFont = findViewById(R.id.btnChangeFont);
        btnChangeFont.setOnClickListener(v -> {
            // Font hệ thống: MONOSPACE, style BOLD
            btnChangeFont.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
        });

        btnChangeFont2 = findViewById(R.id.btnChangeFont2);
        btnChangeFont2.setOnClickListener(v -> {
            // Font hệ thống: SERIF, style BOLD_ITALIC
            btnChangeFont2.setTypeface(Typeface.SERIF, Typeface.BOLD_ITALIC);
        });
    }
}

Bước 4: Cấu hình 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. Nhấn từng nút để thấy font thay đổi:

  • Nút 1: Monospace + Bold (chữ đều, dày)
  • Nút 2: Serif + Bold Italic (chữ có chân, nghiêng, dày)

Cách đặt font chữ tùy chỉnh cho Button trong Android Cách đặt font chữ tùy chỉnh cho Button trong Android

Các font hệ thống có sẵn (Typeface constants)

Hằng số Tên font Đặc điểm
Typeface.DEFAULT Droid Sans / Roboto Font mặc định hệ thống
Typeface.SANS_SERIF Roboto Không chân, hiện đại
Typeface.SERIF Noto Serif Có chân, truyền thống
Typeface.MONOSPACE Droid Sans Mono Cố định chiều rộng, code
Typeface.DEFAULT_BOLD Roboto Bold Mặc định đậm

Các style (style constants)

  • Typeface.NORMAL (0)
  • Typeface.BOLD (1)
  • Typeface.ITALIC (2)
  • Typeface.BOLD_ITALIC (3)

Kết hợp: setTypeface(typeface, style) hoặc setTypeface(Typeface.create(typeface, style))

Sử dụng Font tùy chỉnh (Custom Font từ file .ttf/.otf)

1. Chuẩn bị file font

Tạo thư mục assets/fonts/ (chuột phải main → New → Folder → Assets Folder), copy file font (ví dụ: myfont.ttf) vào.

2. Load và áp dụng

// Cách 1: Typeface.createFromAsset (cũ, vẫn dùng được)
Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
button.setTypeface(customFont);

// Cách 2: ResourcesCompat (API 16+, khuyến nghị)
Typeface customFont = ResourcesCompat.getFont(this, R.font.myfont); // Xem cách 3

// Cách 3: Font resource (API 26+ / Support Library 26+)
// Đặt file .ttf vào res/font/myfont.ttf (tự động tạo R.font.myfont)
// Trong XML:
<Button
    android:fontFamily="@font/myfont"
    ... />

// Trong code (API 16+ với support lib):
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
button.setTypeface(typeface);

3. XML attribute (API 16+ với AppCompat / API 26+ native)

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Font tùy chỉnh từ XML"
    android:fontFamily="@font/myfont"
    android:textStyle="bold|italic" />

Lưu ý hiệu năng

  • Cache Typeface: Tạo Typeface một lần (static/singleton), dùng lại nhiều View. Việc tạo Typeface từ asset tốn tài nguyên.
  • Font resource (res/font/) tự động cache và tối ưu hơn assets/
  • Downloadable Fonts (Google Fonts): Tải font khi cần, chia sẻ giữa apps, tiết kiệm dung lượng APK

Best Practice hiện đại

// Trong Application class hoặc singleton
public class FontCache {
    private static final Map<String, Typeface> cache = new HashMap<>();

    public static Typeface getTypeface(Context context, String assetPath) {
        synchronized (cache) {
            if (!cache.containsKey(assetPath)) {
                Typeface tf = Typeface.createFromAsset(context.getAssets(), assetPath);
                cache.put(assetPath, tf);
            }
            return cache.get(assetPath);
        }
    }
}

// Sử dụng:
button.setTypeface(FontCache.getTypeface(this, "fonts/myfont.ttf"));