Skip to content

Instantly share code, notes, and snippets.

@TylerMcCraw
Created August 22, 2022 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TylerMcCraw/38dc71984612182850c72a59002e7824 to your computer and use it in GitHub Desktop.
Save TylerMcCraw/38dc71984612182850c72a59002e7824 to your computer and use it in GitHub Desktop.
Helper sealed class for handling text from Strings and from string resources
/**
* Taken from https://github.com/AdamMc331/TOA/blob/development/app/src/main/java/com/adammcneilly/toa/core/ui/UIText.kt
*/
import android.content.Context
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
/**
* This is a sealed class that contains all of the different ways text can be presented to the UI.
*/
sealed class UIText {
data class StringText(val value: String) : UIText()
data class ResourceText(@StringRes val value: Int) : UIText()
}
/**
* Evaluates the value of this [UIText] based on its type.
*
* @param[context] If necessary, use this to evaluate a string resource.
*/
fun UIText.getString(context: Context): String {
return when (this) {
is UIText.StringText -> this.value
is UIText.ResourceText -> context.getString(this.value)
}
}
/**
* A helper function that allows to get strings from a [Composable] context.
*/
@Composable
fun UIText.getString(): String {
return this.getString(LocalContext.current)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment