Kotlin Android-是否有一种方法只能在一个类中定义一次View?

问题描述 投票:0回答:1

在我的代码中,我使用以下XML视图:

        val googleButton: Button = findViewById<View>(R.id.google_login) as Button
        val loginWithEmailText: TextView = findViewById(R.id.login_with_email_text)
        val emailLoginButton: Button = findViewById(R.id.email_login_button)
        val createAccountButton: Button = findViewById(R.id.email_create_account_button)

此代码是从我的Kotlin类中的函数中提取的。每当我必须访问这些视图时,都需要重新编写此代码。

我有什么办法可以只在班级代码中的一个地方访问它们?我尝试将它们放在外面,但该应用程序无法启动。

谢谢

android kotlin
1个回答
1
投票

您需要将这些字段定义为类的一部分,并在为Activity / Fragment设置布局资源后对其进行初始化。如果将这些行1:1放在类主体中,则初始化将失败,因为布局尚未膨胀。

请熟悉生命周期的概念,以便您了解如何使用方法查看相关主题:https://developer.android.com/guide/components/activities/activity-lifecycle

请查看此代码段以获取示例代码:

class MyActivity: Activity() {
    lateinit var textView: TextView
    lateinit var button: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        // initialize your views here
        textView = findViewById(R.id.text_view_id)
        button = findViewById(R.id.button_id)
    }

    fun someOtherFunction(){
        // you can reference your views here like normal properties
        button.setOnClickListener { v -> callAnotherFunction() }
        // ...
    }
}

由于您使用的是Android,您可能有兴趣使用Kotlin合成属性来引用视图,而没有找到它们的整个样板:https://antonioleiva.com/kotlin-android-extensions/。建议不要再使用它了,但在某些情况下还是很方便的。

© www.soinside.com 2019 - 2024. All rights reserved.