ในขณะที่ทำการ internalization ในแอปพลิเคชัน Android เราควรรู้ว่าภาษาปัจจุบันในอุปกรณ์ Android คืออะไร ตัวอย่างนี้สาธิตวิธีรับภาษาปัจจุบันในอุปกรณ์ Android
ขั้นตอนที่ 1 − สร้างโครงการใหม่ใน Android Studio ไปที่ไฟล์ ⇒ โครงการใหม่และกรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโครงการใหม่
ขั้นตอนที่ 2 − เพิ่มรหัสต่อไปนี้ใน res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://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 − เพิ่มรหัสต่อไปนี้ใน 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 name " + country);
}
});
}
} ในโค้ดด้านบนนี้ เราได้ใช้คลาส Locale เพื่อรับภาษาที่แสดงและประเทศดังที่แสดงด้านล่าง -
String languagename = Locale.getDefault().getDisplayLanguage(); String country = Locale.getDefault().getCountry();
มาลองเรียกใช้แอปพลิเคชันของคุณกัน ฉันคิดว่าคุณได้เชื่อมต่ออุปกรณ์มือถือ Android จริงกับคอมพิวเตอร์ของคุณ ในการรันแอพจาก android studio ให้เปิดไฟล์กิจกรรมของโปรเจ็กต์แล้วคลิก Runicon จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก แล้วตรวจสอบอุปกรณ์มือถือของคุณซึ่งจะแสดงหน้าจอเริ่มต้นของคุณ -

ในผลลัพธ์ข้างต้น มันจะแสดงหน้าจอเริ่มต้นเมื่อผู้ใช้คลิกที่ปุ่ม มันจะแสดงชื่อประเทศและภาษาดังที่แสดงด้านล่าง -
