How to use string resources in Android Jetpack Compose?

There’s androidx.compose.ui.res package containing functions for loading string resources as well as other resource types.

string

You can get a string using stringResource() function, for example:

...
import androidx.compose.ui.res.stringResource

@Composable
fun StringResourceExample() {
  Text(
    // a string without arguments
    text = stringResource(R.string.app_name)
  )

  Text(
    // a string with arguments
    text = stringResource(R.string.greeting, "World")
  )
}

string array

Can be obtained using stringArrayResource() function:

val planets = stringArrayResource(R.array.planets_array)

plural (quantity string)

As of compose 1.0.0-alpha10 there’s no build-in function for obtaining a plural resource, but you can get the android context via LocalContext and use it the same way as you do it in a view-based app. Even better if you create your own function similar to other resource functions (like Jetcaster compose sample does for example):

// PluralResources.kt

package com.myapp.util

import androidx.annotation.PluralsRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext

@Composable
fun quantityStringResource(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): String {
    return LocalContext.current.resources.getQuantityString(id, quantity, *formatArgs)
}

so you can use it the same way:

val likes = quantityStringResource(R.plurals.likes, 10, 10)

a note about recomposition

As you know, in compose a composable function might be re-executed up to hundreds of times per second during recomposition. If the string you build isn’t trivial and requires some calculation, it’s better to remember the calculation result, so it won’t be re-executed on each recomposition. For example:

...

import androidx.compose.runtime.remember

@Composable
fun BirthdayDateComposable(username: String, dateMillis: Long) {
  // formatDate() function will be executed only if dateMillis value 
  // is changed, otherwise the remembered value will be used
  val dateStr = remember(dateMillis) {
    formatDate(dateMillis)
  }

  Text(
    text = stringResource(R.string.birthday_date, dateStr)
  )
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)