getString Outside of a Context or Activity

后端 未结 12 2091
遥遥无期
遥遥无期 2020-11-28 01:12

I\'ve found the R.string pretty awesome for keeping hardcoded strings out of my code, and I\'d like to keep using it in a utility class that works with models i

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 01:36

    You can do this in Kotlin by creating a class that extends Application and then use its context to call the resources anywhere in your code

    Your App class will look like this

     class App : Application() {
        override fun onCreate() {
            super.onCreate()
            context = this
        }
    
        companion object {
            var context: Context? = null
                private set
        }
    }
    

    Declare your Application class in AndroidManifest.xml (very important)

    
            
                
                    
    
                    
                
            
    
            
        
    

    To access e.g. a string file use the following code

    App.context?.resources?.getText(R.string.mystring)
    

提交回复
热议问题