[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)
반응형
'Mobile > 🔰Kotiln' 카테고리의 다른 글
[Kotlin] Android OutOfMemoryError (0) | 2022.08.27 |
---|---|
[Kotlin] Local Storage에 logcat파일 만들기 (0) | 2022.08.25 |
[Kotlin] Firebase 연동 & Realtime Database 조작 (0) | 2022.04.03 |
[Kotlin] Java에서 Kotlin 으로 Migration 작업 (2) (0) | 2021.02.08 |
[Kotlin] Java에서 Kotlin 으로 Migration 작업 (1) (0) | 2021.02.02 |