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 Software Engineer (f/m/d)

    Paradox Cat GmbH
    Munich
    • Full Time
    apply now

    Mobile Engineer

    OLX Group
    Remote, Portugal, Spain, Romania, Poland
    • Full Time
    apply now

    Kotlin Multiplatform Mobile Developer

    Touchlab
    Remote
    • Full Time
    apply now
Load more listings

OUR VIDEO RECOMMENDATION

,

Overview of UI testing in Compose

Jetpack Compose has no views, so how do we test it? Come learn about the basics of UI testing in Jetpack Compose.
Watch Video

Overview of UI testing in Compose

Michael Bailey
Distinguished Engineer
American Express

Overview of UI testing in Compose

Michael Bailey
Distinguished Engine ...
American Express

Overview of UI testing in Compose

Michael Bailey
Distinguished Engineer
American Express

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
Modern mobile applications are already quite serious enterprise projects that are developed by hundreds…
READ MORE
blog
In this part of the series, we will plan our first screen in Jetpack…
READ MORE
blog
We’ll be selecting a time whenever a user presses a number key. Following points…
READ MORE
blog
This is part of a multi-part series about learning to use Jetpack Compose through…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Menu