Resource Uri 경로 얻기 (Drawable, Raw ...)
Resource Uri
- 운영중인 자사 앱에서는 현재 Glide 이미지 라이브러리를 사용
- 서버에서 RESTful API로 받아온 JSON 내부 Image 배열 값이 비어있다면, 이미지 Resource의 경로를 가져와 Glide에 사용하려는 목적으로 찾아본 Resource Uri Path 얻는 방법
Default
Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(R.raw.test_image))
.appendPath(resources.getResourceTypeName(R.raw.test_image))
.appendPath(resources.getResourceEntryName(R.raw.test_image))
.build()
.toString()
위 방법으로 drawable / raw 등 Resource Uri Path를 얻을 수 있습니다.
단, 사용 지점마다 매번 BoilerPlate Code가 발생하고, ResourceID (R.raw.image) 값을 잘못 입력할 수도 있다는 점이 발생하기 때문에 저는 Kotlin Extenstion Function (Int)를 선언하고 사용하도록 수정하였습니다
Kotlin Extenstion Function (Int)
// Kotlin Extenstion Function (Int)
fun Int.getResourceUri(context: Context): String {
return context.resources.let {
Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(it.getResourcePackageName(this)) // it : resources, this : ResId(Int)
.appendPath(it.getResourceTypeName(this)) // it : resources, this : ResId(Int)
.appendPath(it.getResourceEntryName(this)) // it : resources, this : ResId(Int)
.build()
.toString()
}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
// 사용 1
R.raw.test_image.getResourceUri(mContext)
Glide.with(this)
.load(R.raw.test_image.getResourceUri(mContext)
.into(binding.imageView)
// 사용 2
val resId = R.raw.test_image
Glide.with(this)
.load(resId.getResourceUri(mContext))
.into(binding.imageView)
이렇게 Extenstion Function으로 선언해놓고 Resource ID에 바로 함수호출로 Uri Path를 얻어 사용이 가능하게 됩니다