Skip to content

Instantly share code, notes, and snippets.

@JulienArzul
Last active November 7, 2019 00:35
Show Gist options
  • Save JulienArzul/6ff0d82ce7d0ebe875b75f171286b8a0 to your computer and use it in GitHub Desktop.
Save JulienArzul/6ff0d82ce7d0ebe875b75f171286b8a0 to your computer and use it in GitHub Desktop.
package com.yourpackage
import android.content.Context
import android.os.Parcelable
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import kotlinx.android.parcel.Parcelize
import java.io.Serializable
sealed class AndroidStringResource : Parcelable {
companion object {
fun from(stringValue: String): AndroidStringResource {
return ActualStringResource(stringValue)
}
fun from(@StringRes stringResourceId: Int, vararg formatArgs: Serializable): AndroidStringResource {
return LocalResIdStringResource(stringResourceId, formatArgs.toList())
}
fun fromPlural(@PluralsRes pluralResourceId: Int, quantity: Int, vararg formatArgs: Serializable): AndroidStringResource {
return PluralResIdStringResource(pluralResourceId, quantity, formatArgs.toList())
}
}
abstract fun getValue(context: Context): String
}
@Parcelize
private data class ActualStringResource(private val actualString: String) : AndroidStringResource() {
override fun getValue(context: Context): String {
return actualString
}
}
@Parcelize
private data class LocalResIdStringResource(@StringRes private val stringResourceId: Int,
private val resourceFormatArgs: List<Serializable>? = null) : AndroidStringResource() {
override fun getValue(context: Context): String {
return context.getString(stringResourceId, *(resourceFormatArgs?.toTypedArray() ?: emptyArray()))
}
}
@Parcelize
private data class PluralResIdStringResource(@PluralsRes private val pluralResourceId: Int,
private val quantity: Int,
private val resourceFormatArgs: List<Serializable>? = null) : AndroidStringResource() {
override fun getValue(context: Context): String {
return context.resources.getQuantityString(pluralResourceId, quantity, *(resourceFormatArgs?.toTypedArray() ?: emptyArray()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment