Kotlin:使用Application类获取全局Context

今天碰到一个群友说起application类,想着用kotlin写一下。

kotlin没有static类型,只能用伴生对象了。

很简洁:以后就可以直接在任意的类里面使用WdTools.getContext()获取Context对象了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class WdTools:Application(){
companion object {
var _context:Application? = null
fun getContext():Context{
return _context!!
}

}

override fun onCreate() {
super.onCreate()
_context = this
}



}

null

最后别忘记在manifest注册:ok。

1
2
<application
android:name=".WdTools"

null