Skip to content

Instantly share code, notes, and snippets.

@nicbell
Created December 8, 2022 13:00
Show Gist options
  • Select an option

  • Save nicbell/6ebcd373c4650751256f28131452c20c to your computer and use it in GitHub Desktop.

Select an option

Save nicbell/6ebcd373c4650751256f28131452c20c to your computer and use it in GitHub Desktop.

Revisions

  1. nicbell created this gist Dec 8, 2022.
    30 changes: 30 additions & 0 deletions UIString.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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)