Building an effective abstraction layer for UI resources on Android

Learn how to create a flexible, type-safe abstraction layer for managing UI resources, such as strings and drawables, in Android development.

Michell Bak
6 min readAug 4, 2024
Abstraction layers and UI resources on Android. Generated by DALL·E 3.

As Android developers, we often find ourselves in situations where we need to reference various UI resources in domain models, use cases, state mappers or viewmodels.

It’s very common to use resource identifiers in these situations, for example R.string.description or R.drawable.logo if you need to reference a string resource or a drawable (image), respectively.

While this works, it does have some drawbacks:

  • No type safety
  • Difficult to unit test
  • Limited flexibility
  • A Context instance is often required in non-UI code in order to use resources

To fix these issues, we need to add an abstraction layer.

Let’s start with the basics and introduce a sealed class called UiResource:

@Immutable
sealed class UiResource<T> : Serializable {
abstract fun resolve(context: Context): T
}

--

--