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

วิธีอ่านค่าจาก string.xml ใน Android

ภาพรวม

ตัวอย่างนี้แสดงวิธีเข้าถึง String Resource จาก strings.xml ทั้งใน XML Layout และ Java/Kotlin Code

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

Android Studio → File → New Project

ขั้นตอนที่ 2: กำหนด String (res/values/strings.xml)

<resources>
    <string name="app_name">My Application</string>
    <string name="welcome_message">Welcome to my Android App!</string>
    <string name="button_text">Click Me</string>
    <string name="formatted_text">Hello, %1$s! You have %2$d new messages.</string>
</resources>

ขั้นตอนที่ 3: ใช้ใน XML Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    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:text="@string/welcome_message"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

ขั้นตอนที่ 4: ใช้ใน Java/Kotlin Code

Java

package com.example.stringdemo;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        TextView textView = findViewById(R.id.textView);
        Button button = findViewById(R.id.button);

        // 1. อ่าน String ธรรมดา
        String welcome = getString(R.string.welcome_message);
        textView.setText(welcome);

        // 2. อ่าน String พร้อม Formatting (ต้องใช้ getString(int, Object...))
        String name = "John";
        int count = 5;
        String formatted = getString(R.string.formatted_text, name, count);
        // ผลลัพธ์: "Hello, John! You have 5 new messages."

        // 3. ตั้งค่า Button Text
        button.setText(R.string.button_text); // รับ ResId โดยตรงได้
    }
}

Kotlin

package com.example.stringdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import android.widget.Button

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

        val textView = findViewById<TextView>(R.id.textView)
        val button = findViewById<Button>(R.id.button)

        // 1. อ่าน String ธรรมดา
        val welcome = getString(R.string.welcome_message)
        textView.text = welcome

        // 2. Formatting
        val name = "John"
        val count = 5
        val formatted = getString(R.string.formatted_text, name, count)

        // 3. Button
        button.setText(R.string.button_text)
    }
}

ขั้นตอนที่ 5: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.stringdemo">
    <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/Theme.StringDemo">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

การทดสอบ

รันแอป - จะแสดงข้อความจาก String Resource

Best Practices สำหรับ String Resources

1. ตั้งชื่อเป็นระบบ (Naming Convention)

<string name="login_button_text">Sign In</string>
<string name="error_network_unavailable">Network unavailable. Please try again.</string>
<string name="label_user_email">Email Address</string>

2. ใช้ Formatting แทนการ Concatenate

<!-- ดี -->
<string name="welcome_user">Welcome, %1$s!</string>

<!-- หลีกเลี่ยง -->
<string name="welcome_user_bad">Welcome, </string> <!-- ต้อง concat ในโค้ด -->

3. ใช้ Quantity Strings (Plurals) สำหรับจำนวน

<!-- res/values/plurals.xml -->
<plurals name="item_count">
    <item quantity="zero">No items</item>
    <item quantity="one">%d item</item>
    <item quantity="other">%d items</item>
</plurals>

// ใช้งาน
getResources().getQuantityString(R.plurals.item_count, count, count)

4. แยกไฟล์สำหรับ Module ใหญ่

  • strings.xml - String หลัก
  • strings_auth.xml - Auth/Login
  • strings_settings.xml - Settings

สรุป

  • XML: @string/name
  • Java: getString(R.string.name) หรือ getString(R.string.name, args...)
  • Kotlin: getString(R.string.name) หรือ getString(R.string.name, args...)
  • View.setText(): รับ ResId โดยตรง setText(R.string.name)