Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ Font Awesome ในแอป Android Native ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการใช้ฟอนต์แบบกำหนดเอง (Custom Font) เช่น Font Awesome ในแอป Android Native โดยใช้ Kotlin

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (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"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Have a nice day"
        android:textColor="@android:color/holo_purple"
        android:textSize="36sp"
        android:textStyle="bold" />
</RelativeLayout>

ขั้นตอนที่ 3: เพิ่มไฟล์ฟอนต์

  1. สร้างโฟลเดอร์ assets (คลิกขวาที่ main > New > Folder > Assets Folder)
  2. คัดลอกไฟล์ฟอนต์ (เช่น fontawesome-webfont.ttf หรือ VeganStylePersonalUse-5Y58.ttf) วางในโฟลเดอร์ assets

ขั้นตอนที่ 4: เขียนโค้ด MainActivity.kt

import android.graphics.Typeface
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val textView: TextView = findViewById(R.id.textView)
        // โหลดฟอนต์จาก assets
        val font = Typeface.createFromAsset(assets, "VeganStylePersonalUse-5Y58.ttf")
        textView.typeface = font
    }
}

ขั้นตอนที่ 5: ตั้งค่า AndroidManifest.xml

ใช้การตั้งค่ามาตรฐาน (หมายเหตุ: โค้ดต้นฉบับมี typo `</applicationv>` ควรเป็น `</application>`)

ทดสอบการทำงาน

รันแอป ข้อความใน TextView จะแสดงด้วยฟอนต์ที่กำหนดเอง

ข้อมูลเพิ่มเติม

  • Font Awesome: ต้องดาวน์โหลดไฟล์ .ttf จากเว็บไซต์ Font Awesome แล้ววางใน assets
  • Android 8.0+ (API 26+): สามารถใช้ Fonts in XML วางไฟล์ .ttf ใน res/font/ แล้วตั้งค่าใน XML ได้โดยตรง: android:fontFamily="@font/fontawesome"
  • Downloadable Fonts: ใช้ Google Fonts Provider ดาวน์โหลดฟอนต์เมื่อรันไทม์ ลดขนาด APK