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

วิธีดึงภาษาปัจจุบันที่เลือกในอุปกรณ์ Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการดึงภาษา (Locale) ที่ผู้ใช้เลือกตั้งค่าไว้ในอุปกรณ์ Android โดยใช้ Locale.getDefault() และ 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: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="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center_horizontal"
        android:textColor="@android:color/holo_blue_bright"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

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

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.Locale

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)
        val currentLocale = Locale.getDefault()
        textView.text = "Current device language: ${currentLocale.displayLanguage}\n" +
            "Country: ${currentLocale.displayCountry}\n" +
            "Language Code: ${currentLocale.language}\n" +
            "Country Code: ${currentLocale.country}"
    }
}

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

ใช้การตั้งค่ามาตรฐาน

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

รันแอป จะแสดงชื่อภาษา ประเทศ และรหัสภาษา/ประเทศของอุปกรณ์

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

  • Locale.getDefault(): คืนค่า Locale ปัจจุบันของระบบ (ขึ้นกับการตั้งค่าผู้ใช้)
  • Configuration.locales (API 24+): ใช้ resources.configuration.locales.get(0) สำหรับรายการภาษาที่รองรับหลายภาษา
  • เปลี่ยนภาษาในแอป: ใช้ LocaleList และ Configuration.setLocales() (API 24+) หรือ resources.updateConfiguration() (Deprecated)
  • Best Practice: ให้แอปรองรับหลายภาษาโดยใช้ String Resources ใน res/values-/strings.xml ระบบจะเลือกอัตโนมัติ
  • displayLanguage vs language: displayLanguage แสดงชื่อภาษาในภาษาปัจจุบัน language คืนรหัส ISO 639-1 (เช่น "th", "en")