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

วิธีดูภาษาปัจจุบันในอุปกรณ์ Android

การตรวจสอบภาษาและประเทศในอุปกรณ์ Android

เมื่อพัฒนาแอปพลิเคชันรองรับหลายภาษา (Internationalization) ควรทราบภาษาและประเทศปัจจุบันของอุปกรณ์

ขั้นตอนการทำงาน

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

ไปที่ File → New Project ใน Android Studio

ขั้นตอนที่ 2: เพิ่มเลย์เอาต์ใน res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="#dde4dd"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:id="@+id/language"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/click"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click" />
</LinearLayout>

ขั้นตอนที่ 3: เพิ่มโค้ด Java ใน src/MainActivity.java

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    TextView language;

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

        language = findViewById(R.id.language);
        Button button = findViewById(R.id.click);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String languageName = Locale.getDefault().getDisplayLanguage();
                String country = Locale.getDefault().getCountry();
                language.setText("Language: " + languageName + " Country: " + country);
            }
        });
    }
}

โค้ดสำคัญ:

String languageName = Locale.getDefault().getDisplayLanguage();
String country = Locale.getDefault().getCountry();
  • Locale.getDefault() ดึง Locale เริ่มต้นของอุปกรณ์
  • getDisplayLanguage() ชื่อภาษาที่ผู้ใช้เข้าใจ (เช่น "ไทย", "English")
  • getCountry() รหัสประเทศ ISO 3166-1 alpha-2 (เช่น "TH", "US")

การทดสอบ

  1. รันแอปพลิเคชัน แสดงหน้าจอเริ่มต้นพร้อมปุ่ม Click
  2. กดปุ่ม Click → TextView จะแสดงภาษาและประเทศ (เช่น "Language: Thai Country: TH")