Kotlin 中布局的可见性
Posted
技术标签:
【中文标题】Kotlin 中布局的可见性【英文标题】:visibility of a layout in Kotlin 【发布时间】:2021-02-11 08:11:28 【问题描述】:我有一个布局,我想在单击按钮时使其可见(首先是“GONE”)。
<include
android:id="@+id/registration_layout"
layout="@layout/user_registration"
android:visibility="gone"/>
<include
android:id="@+id/login_layout"
layout="@layout/login"
android:visibility="gone"/>
这是我在 xml 文件中包含的内容
fun onClickLogin(view: View)
val login_layout = R.id.login_layout as Layout
val registration_layout = R.id.login_layout as Layout
login_layout.visibility = View.VISIBLE
val btn_login = R.id.registration as Button
val btn_registration = R.id.registration as Button
btn_login.visibility = View.VISIBLE
在我的 kotlin 文件中,按钮的可见性有效,但布局无效...有什么建议吗?谢谢!
【问题讨论】:
再次查看您的代码 ``` val login_layout = R.id.login_layout as Layout val registration_layout = R.id.login_layout as Layout ```registration_layout val 和 login_layout val 具有相同的参考 xml 。 .. 【参考方案1】:不是投射到Layout
,而是将布局投射到View
:
fun onClickLogin(view: View)
val login_layout = R.id.login_layout as View //note : from import android.view.View
val registration_layout = R.id.registration_layout as View //note: you wrote R.id.login_layout
login_layout.visibility = View.VISIBLE
registration_layout.visibility = View.GONE
val btn_login = R.id.btn_login as Button
val btn_registration = R.id.registration as Button
btn_login.visibility = View.VISIBLE
btn_registration = View.GONE
【讨论】:
但是现在点击按钮应用程序崩溃,我不知道为什么...... @Malopieds 你是否将布局转换为View
?
只需将其替换为 val loginLayout = findViewById<View>(R.id.login_layout)
即可,谢谢!以上是关于Kotlin 中布局的可见性的主要内容,如果未能解决你的问题,请参考以下文章