Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 이미지 이름으로 리소스 ID(Resource ID)를 가져오는 방법

개요

Android 앱을 개발하다 보면 이미지 파일의 정확한 리소스 ID를 직접 알 수 없고, 파일 이름만 알고 있는 경우가 종종 있습니다. 예를 들어 서버에서 받은 문자열 값으로 동적으로 이미지를 로드해야 할 때가 대표적입니다. 이럴 때 getResources().getIdentifier() 메서드를 사용하면 리소스 이름만으로 해당 리소스의 ID를 손쉽게 얻을 수 있습니다.

이 글에서는 이미지(드로어블)의 이름을 알고 있을 때 그 리소스 ID를 가져오는 방법을 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계 — 레이아웃 작성 (res/layout/activity_main.xml)

아래 코드를 res/layout/activity_main.xml 파일에 추가합니다. 화면에는 ImageView와 리소스 ID 값을 표시할 TextView가 포함되어 있습니다.

<?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 코드 작성 (src/MainActivity.java)

핵심은 다음 코드 한 줄입니다. 리소스 이름과 리소스 타입, 패키지 이름을 인자로 전달하면 해당 리소스의 ID가 반환됩니다.

int resID = getResources().getIdentifier(mDrawableName, "drawable", getPackageName());

전체 MainActivity 코드는 아래와 같습니다.

package app.tutorialspoint.com.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        // 리소스 ID를 찾고 싶은 이미지의 이름
        String mDrawableName = "ic_launcher_background";

        // 이름을 기반으로 리소스 ID 조회
        int resID = getResources().getIdentifier(mDrawableName, "drawable",
                getPackageName());

        TextView tvResourceId = findViewById(R.id.tvResourceId);
        tvResourceId.setText(String.valueOf(resID));
    }
}

getIdentifier() 메서드 파라미터 설명

  • name: 찾고자 하는 리소스의 이름 (예: "ic_launcher_background")
  • defType: 리소스 타입 (예: "drawable", "string", "id" 등)
  • defPackage: 리소스가 포함된 패키지 이름 (보통 getPackageName() 사용)

참고로, 해당 이름의 리소스가 존재하지 않으면 이 메서드는 0을 반환하므로, 실제 프로젝트에서는 반환값이 0인지 반드시 확인하는 것이 좋습니다.

4단계 — AndroidManifest.xml 수정

아래 코드를 androidManifest.xml에 추가합니다.

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

    <uses-permission android:name="android.permission.VIBRATE" />

    <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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 휴대폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바에서 Run 아이콘을 클릭하세요. 실행 옵션으로 자신의 모바일 기기를 선택하면, 연결된 기본 화면에 아래와 같이 TextView에 조회된 리소스 ID 숫자 값이 표시됩니다.

Android에서 이미지 이름으로 리소스 ID(Resource ID)를 가져오는 방법

마무리 및 주의사항

이처럼 getIdentifier()를 활용하면 문자열 형태의 리소스 이름만으로도 동적으로 리소스에 접근할 수 있습니다. 다만 이 방식은 리플렉션 기반으로 동작하기 때문에 성능이 다소 떨어질 수 있으며, R.drawable 클래스를 통한 정적 참조보다 느립니다. 따라서 리소스 이름이 빌드 시점에 확정되어 있다면 R 클래스 상수를 사용하는 것이 권장되며, getIdentifier()는 이름이 런타임에 결정되는 경우에 사용하는 것이 좋습니다.