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 Developer

    SumUp
    Berlin
    • Full Time
    apply now

    Senior Android Engineer

    Carly Solutions GmbH
    Munich
    • Full Time
    apply now

OUR VIDEO RECOMMENDATION

, ,

Boosting Compose UI from Sluggish to Snappy

Join us on an enlightening quest as we unravel the realm of Compose UI performance. With a multitude of tools at our disposal, the challenge lies in knowing where to start and how to choose.
Watch Video

Boosting Compose UI from Sluggish to Snappy

Akshay Chordiya & Tasha Ramesh
Android Developer & Android
Tinder

Boosting Compose UI from Sluggish to Snappy

Akshay Chordiya & ...
Android Developer & ...
Tinder

Boosting Compose UI from Sluggish to Snappy

Akshay Chordiya ...
Android Developer & Andro ...
Tinder

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