[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)
'Andorid' 카테고리의 다른 글
[Android / Java] firebase를 이용한 구글 로그인 연동 (2) | 2022.03.22 |
---|---|
[Android] firebase 연동 (최신버전) (2) | 2022.03.22 |
[Kotlin] Java에서 Kotlin 으로 Migration 작업 (2) (0) | 2021.02.08 |
[Kotlin] Java에서 Kotlin 으로 Migration 작업 (1) (0) | 2021.02.02 |
[Android / Java] ListView 특정 아이템 클릭 이벤트 막기 (0) | 2021.01.18 |