Kotlin中的全局对象声明 [英] Global object declaration in kotlin

查看:480
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆