Last active
September 3, 2023 13:03
-
-
Save Abdallah-Abdelazim/8f46e0487911b48cd9449a25ae365097 to your computer and use it in GitHub Desktop.
UiText: use Android's String Resources in the whole project.
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
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()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on: https://youtube.com/shorts/JnJ_CaEMeEQ