Skip to content

Instantly share code, notes, and snippets.

@Abdallah-Abdelazim
Last active September 3, 2023 13:03
Show Gist options
  • Save Abdallah-Abdelazim/8f46e0487911b48cd9449a25ae365097 to your computer and use it in GitHub Desktop.
Save Abdallah-Abdelazim/8f46e0487911b48cd9449a25ae365097 to your computer and use it in GitHub Desktop.
UiText: use Android's String Resources in the whole project.
package com.example.app
import android.content.Context
import androidx.annotation.StringRes
sealed class UiText {
data class DynamicString(val value: String) : UiText()
data class StringResource(
@StringRes val resId: Int,
val args: List<Any> = emptyList()
) : UiText()
fun asString(context: Context): String {
return when (this) {
is DynamicString -> value
is StringResource -> context.getString(
resId, *args.toTypedArray()
)
}
}
companion object {
/**
* Creates a [UiText] from a [String].
*/
fun from(value: String): UiText {
return DynamicString(value)
}
/**
* Creates a [UiText] from a [StringRes] and its arguments.
*/
fun from(@StringRes resId: Int, vararg args: Any): UiText {
return StringResource(resId, args.toList())
}
}
}
@Abdallah-Abdelazim
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment