Created
December 8, 2022 13:00
-
-
Save nicbell/6ebcd373c4650751256f28131452c20c to your computer and use it in GitHub Desktop.
UIString: Allows switching between strings and string resources without additional logic in the view. Also avoids accessing Android platform classes outside of the view to resolve strings.
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
import android.content.res.Resources | |
import android.os.Parcelable | |
import androidx.annotation.StringRes | |
import kotlinx.parcelize.Parcelize | |
/** | |
* UIString: Allows switching between strings and string resources without additional | |
* logic in the view. Also avoids accessing Android platform classes outside of the view | |
* to resolve strings. | |
*/ | |
sealed class UIString : Parcelable { | |
@Parcelize | |
data class ActualString(val value: String) : UIString() | |
@Parcelize | |
data class StringResource(@StringRes val id: Int) : UIString() | |
/** | |
* Only used in your view | |
*/ | |
fun getString(resources: Resources) = when (this) { | |
is ActualString -> this.value | |
is StringResource -> resources.getString(this.id) | |
} | |
} | |
/** | |
* Helper directly from resources | |
*/ | |
fun Resources.getString(uiString: UIString) = uiString.getString(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment