Skip to content

ResourcesExtensions

燒餅 edited this page Jun 1, 2017 · 2 revisions

来自 ResourcesExtensions.kt 的源码示例:

val Resources.string get() = StringResources(this)

class StringResources internal constructor(private val res: Resources) {
	operator fun get(id: Int) : String? = res.getString(id)
}

该扩展借助 Kotlin 扩展方法、成员变量的特性,为 Android 资源获取提供了更加便利直观的方法。

在 Java 传统写法中,我们需要调用 getter:

context.getResources().getString(R.string.hello_world);

在 Kotlin 中,引入 ResourcesExtensions 后可以这样写:

context.resources.string[R.string.hello_world]

是不是漂亮多了?而且丝毫不影响代码的可读性。

除了 string 资源:还支持下列资源(源码):

val Resources.animation get() = AnimationResources(this)
val Resources.boolean get() = BooleanResources(this)
val Resources.color get() = ColorResources(this)
val Resources.drawable get() = DrawableResources(this)
val Resources.dimension get() = DimensionResources(this)
val Resources.ints get() = IntResources(this)
val Resources.intArrays get() = IntArrayResources(this)
val Resources.layout get() = LayoutResources(this)
val Resources.string get() = StringResources(this)
val Resources.stringArrays get() = StringArrayResources(this)
val Resources.text get() = TextResources(this)
val Resources.quantityString get() = QuantityResources(this)

使用方法和 string 相同。

Clone this wiki locally