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

วิธีดึง Resource ID ของรูปภาพจากชื่อไฟล์ใน Android

การหา Resource ID (R.drawable.xxx) จากชื่อไฟล์สตริง

ตัวอย่างนี้แสดงวิธีใช้ getResources().getIdentifier() เพื่อแปลงชื่อไฟล์รูปภาพ (String) ให้เป็น Resource ID (Integer) แบบ Dynamic

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

Android Studio → File → New Project → กรอกรายละเอียด → Finish

ขั้นตอนที่ 2: Layout - 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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/ivLauncer"
        android:layout_width="match_parent"
        android:layout_height="450dp"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_launcher_background" />
    <TextView
        android:id="@+id/tvResourceId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

ขั้นตอนที่ 3: MainActivity.java

package app.tutorialspoint.com.sample;

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

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String drawableName = "ic_launcher_background";
        
        // ดึง Resource ID จากชื่อ
        int resID = getResources().getIdentifier(
            drawableName, 
            "drawable", 
            getPackageName()
        );
        
        TextView tvResourceId = findViewById(R.id.tvResourceId);
        tvResourceId.setText("Resource ID: " + resID);
        
        Log.d("ResourceID", "Name: " + drawableName + ", ID: " + resID);
    }
}

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.sample">
    <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>

รูปแบบของ getIdentifier()

int getIdentifier(String name, String defType, String defPackage)
Parameterคำอธิบายตัวอย่าง
nameชื่อ Resource (ไม่ต้องมี @drawable/)"ic_launcher"
defTypeประเภท Resource"drawable", "string", "layout", "id", "color", "dimen", "raw", "anim"
defPackagePackage Name ของแอปgetPackageName()

กรณีการใช้งานทั่วไป

1. โหลดรูปภาพแบบ Dynamic

String[] images = {"img1", "img2", "img3", "img4", "img5"};
for (String name : images) {
    int resId = getResources().getIdentifier(name, "drawable", getPackageName());
    if (resId != 0) {
        imageView.setImageResource(resId);
    }
}

2. ดึง String Resource

int stringId = getResources().getIdentifier("app_name", "string", getPackageName());
String appName = getString(stringId);

3. ดึง Layout Resource

int layoutId = getResources().getIdentifier("activity_main", "layout", getPackageName());
setContentView(layoutId);

⚠️ ข้อควรระวัง

  • คืนค่า 0 หากไม่พบ Resource (ต้องเช็คก่อนใช้)
  • ช้ากว่าการอ้างอิง R.xxx โดยตรง (ใช้ Reflection)
  • ProGuard/R8 อาจ obfuscate ชื่อ Resource ให้ใช้ @Keep หรือ keep rules
  • ไม่ทำงานกับ Resource ใน Library Module (ต้องระบุ Package Name ของ Library)

Best Practice

// Cache ID ไว้ใช้ซ้ำ
private static final Map<String, Integer> resourceCache = new HashMap<>();

public int getDrawableId(String name) {
    return resourceCache.computeIfAbsent(name, n -> 
        getResources().getIdentifier(n, "drawable", getPackageName())
    );
}