Kotlin新手求助:如何为Context编写正确的getInteger扩展函数?
Kotlin扩展函数实现资源int值获取的修正方案
嘿,刚接触Kotlin的话,扩展函数确实容易踩点小坑,我来帮你捋捋问题出在哪,以及怎么改~
你的需求回顾
你想把原本通过mContext.resources.getInteger(R.integer.ActivityEditBackup)(也就是你的Code A)获取资源int值的逻辑,改成用扩展函数实现,能直接以this.getInteger(R.integer.ActivityEditBackup)的方式调用,但写的Code B有问题。
先贴一下你的代码:
Code A(正常工作):
mContext.resources.getInteger(R.integer.ActivityEditBackup)
Code B(存在错误):
inline fun <reified T : Activity>Context.getInteger(int id): int { return T.resources.getInteger(id) }
分析Code B的问题
这里有几个明显的错误:
- 语法与类型问题:Kotlin里变量类型是写在变量名后面的,而且基本类型是大写开头的
Int,不是int,所以int id要改成id: Int,返回值int也要换成Int。另外最好加上@IdRes注解,让IDE帮你检查资源ID的合法性。 - 错误的资源获取方式:你用了
T.resources,但T是Activity的类(不是实例),静态访问resources是行不通的——resources是Context实例的属性,不是类属性。 - 多余的泛型:你的扩展函数是给
Context类加的,而Activity本身就是Context的子类,完全不需要用泛型去限定T : Activity,这样反而限制了扩展函数的使用场景(比如Fragment里的Context也没法用了)。
修正后的扩展函数
把这些问题都改了之后,正确的扩展函数应该是这样的:
import android.content.Context import androidx.annotation.IdRes // 若用support库则替换为android.support.annotation.IdRes fun Context.getInteger(@IdRes id: Int): Int { return this.resources.getInteger(id) }
调用方式
现在你就可以在任何Context子类(比如Activity、Fragment里的context)里直接调用了:
- 在Activity中:
val backupValue = getInteger(R.integer.ActivityEditBackup) // 或者显式写this,效果一致 val backupValue2 = this.getInteger(R.integer.ActivityEditBackup) - 在Fragment中:
context?.let { val backupValue = it.getInteger(R.integer.ActivityEditBackup) }
这样就完美实现你想要的调用方式啦~
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

