Andorid
[Kotlin] applicationContext 가져오기
ming.gu
2021. 2. 10. 11:05
[Kotlin] / [코틀린]
ApplicationContext 가져오기
안드로이드에 이 context 라는 것은 매!우! 코딩을 귀찮게 하는 원인이다..
특히 컴포넌트의 color를 변경하거나 resource에 접근할 때도 context를 인자값으로 받는데, 왜 굳이 이런 것에까지 필요한지 모르겠다..
그래서 applicationContext 를 받아와 리소스에 접근하는 것이 효율적으로 판단.
어디서나 접근 할 수 있는 context 를 만들어본다.
App.kt
import android.app.Application
import android.content.Context
class App : Application() {
init{
instance = this
}
companion object {
var instance: App? = null
fun context() : Context {
return instance!!.applicationContext
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!--Permission-->
...
<application
android:name=".App" //Name 추가
android:allowBackup="true"
...
실제 사용할 때는 아래와 같이 이용한다.
tvProgressMessage?.text = App.context().getString(R.string.loading)