Created
August 22, 2022 16:40
-
-
Save TylerMcCraw/38dc71984612182850c72a59002e7824 to your computer and use it in GitHub Desktop.
Helper sealed class for handling text from Strings and from string resources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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