Skip to content

Using @StringRes in kotlin

Devrath edited this page Oct 15, 2023 · 1 revision

Where it can be used

  • Sometimes we face scenarios where we cannot access the context to reference the string resources in the application.
  • Some scenarios are data-classe, sealed-class, etc...
  • In such scenarios we can use it as an integer return type since it returns the memory address of the place string stored in memory.
  • Annotation used is @StringRes.

Code

HomeNavItem.kt

sealed class HomeNavItem(
    val route: String,
    val iconSelected: ImageVector,
    val iconUnSelected: ImageVector,
    @StringRes val title: Int
) {
    // <--------- MyBooks Screen --------->
    object MyBooks : HomeNavItem(
        route = "myBooks",
        title = R.string.str_my_books,
        iconSelected = Icons.Filled.Book,
        iconUnSelected = Icons.Outlined.Book,
    )

    // <--------- BookReviews Screen --------->
    object BookReviews : HomeNavItem(
        route = "bookReviews",
        title = R.string.str_book_reviews,
        iconSelected = Icons.Filled.Reviews,
        iconUnSelected = Icons.Outlined.Reviews,
    )

    // <--------- ReadingList Screen --------->
    object ReadingList : HomeNavItem(
        route = "readingList",
        title = R.string.str_reading_list,
        iconSelected = Icons.Filled.MoreTime,
        iconUnSelected = Icons.Outlined.MoreTime,
    )
}

Usage

  • We can use it as
Text(text = cxt.getString(ref.MyBooks.title))
  • We can see we directly pass the integer value to the getString method.
Clone this wiki locally