안드로이드에서 제공하는 함수 중 이미지를 변경할 수 있는 코드가 있습니다.
public static @NullableDrawablegetDrawable(@NonNullContext context, @DrawableRes int id)
이 코드는 Context에 Null을 허용하지않기 때문에 사용시 주의가 필요합니다.
☁️ [이전] Java Class에서 사용하는 법
tvViewGroup[nSelect].setBackground(ContextCompat.getDrawable(getContext(), R.drawable.shape));
➡️ Java는 getContext()가 Null 인지 체크 할 필요가 없지만 Null 일시 앱이 강제종료 되는 현상이 발생 할 수 있습니다.
☁️ [이전] Kotlin Class에서 사용하는 법
context?.let{
viewDataBinding.btnSpeaker.background= ContextCompat.getDrawable(context, R.drawable.ic_btn_circle)
}
➡️ Kotlin은 Null 체크에 까다롭기 때문에 Context가 Null 인지 확인하고 이미지를 가져와야 합니다.
Java와 Kotlin이 같이 참고하게 되는 이미지 가져오는 공통 함수
/**
* 이미지 가져오기
*/
fun getDrawable(context: Context?, drawable: Int): Drawable? =
if (context == null) null else ContextCompat.getDrawable(context, drawable)
➡️ 알수없는 drawable 값이 들어오더라도 Resources$NotFoundException이 발생 하지않게 예외처리 하였습니다.