Kotlin中的全局对象声明 [英] Global object declaration in kotlin
问题描述
如何像Java TextView tv;
一样在 kotlin 中全局声明对象.
How to declare objects globally in kotlin like in java TextView tv;
.
或任何在不同方法/函数中调用相同变量的方法.
Or any method to call the same variable in different methods/functions.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView: TextView = findViewById(R.id.texfirst) as TextView
textView.setOnClickListener {
Toast.makeText(applicationContext,"Welcome to Kotlin ! $abc "+textView.text, Toast.LENGTH_LONG).show()
}
myFunction(textView)
}
fun myFunction(mtextv : TextView) {
Toast.makeText(applicationContext,"This is new $abc "+mtextv.text, Toast.LENGTH_LONG).show()
}
请参见上面的代码,我使用参数TextView
分隔了函数.我想要第二个功能的TextView
对象.我的问题是:是否可以在不使用参数的情况下调用函数,我是否可以在myFunction()
处获取TextView
对象.
See the above code I've separate function with parameter of TextView
. I want the TextView
object at second function. My question is: Is it possible to call function without parameter and am I able to get TextView
object at myFunction()
.
在Android Studio中学习Kotlin.希望问题很明确.
Learning kotlin in android studio. Hope question is clear .
推荐答案
您提到的是类属性.
对于您的情况,您需要在Activity
类中声明TextView
并通过在onCreate()
中调用findViewById()
进行赋值.
For your case, you need to declare a TextView
in an Activity
class and do the assignment by calling findViewById()
in onCreate()
.
class YourActivity {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.texfirst) as TextView
//implementation
}
fun myFunction() {
Toast.makeText(applicationContext, "This is new $abc " + textView.text, Toast.LENGTH_LONG).show()
}
}
这篇关于Kotlin中的全局对象声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!