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

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Building State Holders in Compose with Molecule: A New Approach to Reusable UI Components

Are your ViewModels exponentially growing out of control as they manage the state for each of your Composables? This talk introduces Molecule, a new library for creating state holders in Jetpack Compose.
Watch Video

Building State Holders in Compose with Molecule: A New Approach to Reusable UI Components

Jack Adams
Senion Android Engineer
Trainline

Building State Holders in Compose with Molecule: A New Approach to Reusable UI Components

Jack Adams
Senion Android Engin ...
Trainline

Building State Holders in Compose with Molecule: A New Approach to Reusable UI Components

Jack Adams
Senion Android Engineer
Trainline

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
Menu