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

Cách lấy ngôn ngữ hiện tại của thiết bị Android bằng Kotlin

Giới thiệu

Ví dụ đơn giản minh họa cách lấy ngôn ngữ (locale) hiện tại đang được chọn trên thiết bị Android và hiển thị tên ngôn ngữ đó bằng Kotlin.

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

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

Android Studio > File > New Project.

Bước 2: 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: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>

Bước 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)
        // Lấy Locale mặc định của hệ thống
        val currentLocale = Locale.getDefault()
        // Lấy tên ngôn ngữ hiển thị (localized)
        val displayLanguage = currentLocale.displayLanguage
        // Lấy mã ngôn ngữ (ISO 639-1), ví dụ: "vi", "en"
        val languageCode = currentLocale.language
        // Lấy quốc gia (ISO 3166-1), ví dụ: "VN", "US"
        val countryCode = currentLocale.country

        textView.text = "Ngôn ngữ thiết bị: $displayLanguage ($languageCode-$countryCode)"
    }
}

Bước 4: AndroidManifest.xml

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

    <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

Chạy app, TextView hiển thị ví dụ: "Ngôn ngữ thiết bị: Tiếng Việt (vi-VN)" hoặc "Device language: English (en-US)".

Mở rộng: Đa ngôn ngữ (Localization) trong App

1. Hỗ trợ nhiều ngôn ngữ (Res values-*)

  • Tạo thư mục res/values-vi/strings.xml (tiếng Việt).
  • Tạo thư mục res/values-en/strings.xml (tiếng Anh).
  • App tự động chọn file strings.xml phù hợp với Locale.getDefault().

2. Thay đổi ngôn ngữ trong App (Runtime) - API 24+ (Android 7.0+)

fun setAppLocale(context: Context, languageCode: String): Context {
    val locale = Locale(languageCode)
    Locale.setDefault(locale)
    val config = context.resources.configuration
    config.setLocale(locale) // API 24+
    // config.setLocales(LocaleList(locale)) // API 24+ (List)
    return context.createConfigurationContext(config)
}

// Usage: Áp dụng cho Activity
override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(setAppLocale(newBase!!, "vi")) // Ép tiếng Việt
}

3. Jetpack AppCompat Delegate (Khuyến nghị cho AppCompat)

// Trong Application class hoặc Activity đầu tiên
AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags("vi"))
  • Yêu cầu androidx.appcompat:appcompat:1.6.0+.
  • Tự động apply cho toàn app, hỗ trợ backup/restore.

4. Lấy danh sách ngôn ngữ hệ thống hỗ trợ

val localeList = resources.configuration.locales // API 24+
// Hoặc
val localeList = LocaleList.getDefault() // API 21+ (deprecated)
for (i in 0 until localeList.size()) {
    val loc = localeList[i]
    println("${loc.displayLanguage} (${loc.language})")
}

Tóm tắt

APIMục đích
Locale.getDefault()Lấy locale hiện tại của JVM/App.
locale.displayLanguageTên ngôn ngữ bản địa hóa (VD: "Tiếng Việt", "English").
locale.languageMã ISO 639-1 (VD: "vi", "en").
locale.countryMã ISO 3166-1 (VD: "VN", "US").
Configuration.setLocale()Thay đổi locale cho Context (API 24+).
AppCompatDelegate.setApplicationLocales()Thay đổi locale toàn app (Jetpack, API 21+).