[英]Android: How to set R.string value from strings.xml to a global constant in Kotlin?
I'm new to Kotlin so maybe I'm missing something obvious, but I couldn't find an answer through Google.我是 Kotlin 的新手,所以也许我遗漏了一些明显的东西,但我无法通过谷歌找到答案。
How can I set the value of a Kotlin constant to a strings.xml resource value?如何将 Kotlin 常量的值设置为 strings.xml 资源值? I've tried to do it like below but it's throwing the following error:
我试过像下面那样做,但它抛出了以下错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
This is my code, the first val declaration fails:这是我的代码,第一个 val 声明失败:
class MainActivity: AppCompatActivity() {
private val STATUS_PREP = getString(R.string.status_prep) //THIS LINE FAILS
private val STATUS_FIGHT = "fight" //res.getString(R.string.status_fight)
private val STATUS_REST = "rest" //res.getString(R.string.status_rest)
private val STATUS_COMPLETE = "complete" //res.getString(R.string.status_complete)
private val STATUS_PAUSED = "paused" //res.getString(R.string.status_paused)
Do this instead.改为这样做。
class MainActivity : AppCompatActivity() {
private val STATUS_PREP: String by lazy {
getString(R.string.status_prep_2)
}
// OR
private lateint var STATUS_PREP: String
override fun onCreate(savedInstanceState: Bundle?) {
// snip
initString()
}
private fun initString() {
STATUS_PREP = getString(R.string.status_prep)
// Init all your string here
}
}
You are getting the exception because context
is not initialized right after an instance of an activity is created.您收到异常是因为在创建活动实例后未立即初始化
context
。
You can create a class that inherits Application class and create inside it static field that will keep reference to application context like this:您可以创建一个继承 Application class 的 class 并在其中创建 static 字段,该字段将保持对应用程序上下文的引用,如下所示:
class MyApplication: Application() {
companion object {
var context: Context? = null; private set
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
}
after that put it's name in AndroidManifest.xml like this:之后将它的名称放在 AndroidManifest.xml 中,如下所示:
<application
android:name="com.yourpackage.MyApplication"
...
// many other tags>
<application>
And then you can simply use it in everywhere in your app like this:然后你可以像这样在你的应用程序的任何地方简单地使用它:
class MainActivity : AppCompatActivity() {
private val STATUS_PREP = MyApplication.context!!.getString(R.string.status_prep)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.