반응형
- getIdentifier()는 이름(String)으로 앱의 리소스 ID를 가져오는 함수입니다.
resources.getIdentifier(name: String, defType: String, defPackage: String)
- name: 찾고 싶은 리소스의 이름 (문자열)
- defType: 리소스의 종류 (drawable, string, layout, id, color 등)
- defPackage: 패키지 이름 (context.packageName을 사용하면 현재 앱의 패키지)
- Drawable 리소스 반환하기
context.resources.getIdentifier("ic_weather_sunny_day", "drawable", context.packageName)
만일 조건에 해당하는 리소스가 존재하지 않으면 0을 반환합니다.
하지만 안드로이드 12부터 Deprecated 되었기 때문에 아래 Reflection 형태로 전환하는 것을 권장합니다.
val resId = try {
val resClass = R.drawable::class.java
val field = resClass.getDeclaredField(resourceName)
field.getInt(null) // 정적 필드에서 ID 가져오기
} catch (e: Exception) {
0
}
val drawable = if (resId != 0) {
ContextCompat.getDrawable(context, resId)
} else {
null
}
반응형