【发布时间】:2020-05-13 10:11:38
【问题描述】:
我正在为主要活动制作第二个屏幕,第二个屏幕(screen_overlay.xml)类似于弹出式覆盖屏幕,用户可以在按下 textView 时随时关闭它。
我遇到的问题是,每次单击“关闭屏幕”文本时,应用程序总是崩溃。我一直在查看有关此的一些参考资料,但几乎所有解决方案都以应用程序崩溃告终。
我发现的大部分解决方案都是用 Java 编写的,所以我尝试在 Kotlin 中进行调整,但我仍然不确定我在哪里遗漏了什么或者下面的 kotlin 代码有问题。
下面是xml代码,
screen_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.testApp.feature.screenView">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/screen_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textView_close_screen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="CLOSE SCREEN"
android:clickable="true"
android:onClick="hideScreen"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
下面是kotlin代码,
screenView.kt
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.app.testApp.R
import kotlinx.android.synthetic.main.screen_overlay.*
class TutorialDialog : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.screen_overlay)
}
fun hideScreen(v: View?){
val v:TextView = findViewById(R.id.textView_close_screen)
v.setOnClickListener{
screen_background.visibility = View.GONE
}
}
}
任何帮助解决此问题的人将不胜感激,谢谢。
【问题讨论】:
-
您一次又一次地添加点击监听器。
hidescreen应该只包含background.visibility = View.GONE -
@Pavneet_Singh 有什么解释为什么
v.setOnClickListener被多次添加?我也曾尝试删除点击监听器,只使用background.visibility = View.GONE,但它仍然崩溃 -
您再次找到视图
findViewById并添加了一个新的侦听器v.setOnClickListener,这已经用android:onClick="hideScreen"完成了 -
有两个问题。首先,为什么要使用嵌套约束布局。第二:您没有在 Activity Oncreate 方法中调用 hide Screen。
-
R.screen_overlay是错字吗?因为您应该使用布局参考调用setContentView,即。R.layout.screen_overlay.