Skip to content

Instantly share code, notes, and snippets.

@nicbell
Created December 8, 2022 13:00
Show Gist options
  • Save nicbell/6ebcd373c4650751256f28131452c20c to your computer and use it in GitHub Desktop.
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.
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