Blog Infos
Author
Published
Topics
,
Published
Topics
,
A context aware string abstraction for Android

 

The Java String type
textView.setText("string")

The Android String resource
textView.setText(R.string.resource)

The magic involved here is that these methods just wrap the context.getString(stringRes) method to create the CharSequence to provide to the original method.

 

data class ErrorMessage(
    @StringRes val messageId: Int = 0,
    val message: String? = null,
)

fun ErrorMessage.getMessage(context: Context) =
    message ?: context.getString(messageId)

To support formatting argument or quantities, the entity could be extended further. Alternatively it would be possible to provide a sealed class to handle all the different use-cases here depending on the actual implementation.

Job Offers

Job Offers


    Senior Android Engineer

    Busuu
    Madrid
    • Full Time
    apply now

    Softwareentwickler Java und Kotlin / Android (w/m/d)

    AVM GmbH
    Berlin
    • Full Time
    apply now

    Mobile Developer Android (m/w/d) Firebase

    REWE digital
    Köln / Cologne
    • Full Time
    apply now
Load more listings

OUR VIDEO RECOMMENDATION

Jobs

The Android String type
textView.setText("value".asAString())
textView.setText(StringResource(R.string.value))

The AString interface is defined to be extensible, so that it’s also possible to encapsulate formatting logic and small conversions or access information directly from the Context provided to the function.

@Parcelize
data class LocalDateFormatAString(
    private val date: LocalDate,
    private val pattern: String,
) : AString {
    override fun invoke(context: Context) =
        date.format(DateTimeFormatter.ofPattern(pattern))
}
@Parcelize
object LocaleAString : AString {
    override fun invoke(context: Context) =
        context.resources.configuration.locales[0].toString()
}

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
In this part of the series, we will plan our first screen in Jetpack…
READ MORE
blog
This is part of a multi-part series about learning to use Jetpack Compose through…
READ MORE
blog
UI created with XML is traditionally tested with Espresso and UIAutomator. However, Jetpack Compose…
READ MORE
blog
It’s been almost a year since I wrote an article on how I handle…
READ MORE

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu