Issue
I have a custom dialog that's initialized in onCreate()
of some Activity. It displays some text and a button. I want the button to close the dialog when clicked. How can I achieve this?
Here's my attempt that fails.
MyActivity.kt
class MyActivity : AppCompatActivity() {
private lateinit var myDialog: Dialog
override fun onCreate(savedInstanceState: Bundle?) {
...
myDialog = Dialog(this)
myDialog.setContentView(R.layout.my_dialog_layout)
val button = myDialog.findViewById<Button>(R.id.closeButton)
button.setOnClickListener {
fun onClick(v: View) {
myDialog.dismiss()
}
}
}
}
my_dialog_layout.xml (I stripped away some properties)
<androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:text="Some Text" />
<Button
android:id="@+id/closeButton"
android:text="Close Dialog" />
</androidx.constraintlayout.widget.ConstraintLayout>
Solution
Just replace
button.setOnClickListener {
fun onClick(v: View) {
myDialog.dismiss()
}
}
with
button.setOnClickListener {
fun onClick(v: View) {
myDialog.dismiss()
}
onClick(it)
}
or to make it more simple
button.setOnClickListener {
myDialog.dismiss()
}
You have declared a nested function onClick
inside the setOnClickListener
lambda. As you have declared a nested function but have not called it inside your Dialog
is not getting dismissed because myDialog.dismiss()
block is not being executed.
Answered By - Alif Hasnain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.