In this article, you’ll learn how to use string resources inside ViewModel
or any place you want, no matter what the source of the string is!
We want to treat all strings in Android as equals, whether they’re from strings.xml
, backend or user-created content. You’ll need an abstraction representing all of these values to do so. We’ll call it StringHolder
.
Luckily, in Kotlin, we can leverage sealed interface
for that:
In code, it’ll look like this:
This can be a domain
layer model if it has some dependencies on Android already. If you’re doing it the proper and fully clean way, then you can use it without the @StringRes
annotation.
Now, we can pass these strings around as if they were equals, but we also need a way to get values through a single function. Here are 3 most common methods for that:
Now that we have our extension functions in place, it’s very easy to use the class in our UI:
If you need it in data
layer classes or Framgents
you can access it through Resources
or Context
: