Shashank Pandey
Shashank Pandey

Reputation: 778

Unable to dismiss BottomSheetDialog

I'm using following approach to create bottomsheet dialog, dialog is creating but I want to dismiss on backpress for that all setup I'm using the code below. But not doing able to dismiss dialog.

 class MainActivity : BaseClass(), View.OnClickListener {
        private lateinit var bottomSheetDialog: BottomSheetDialog
        override fun onCreate(savedInstanceState: Bundle?) {
             super.onCreate(savedInstanceState)
             setContentView(R.layout.activity_main)
             bottomSheetDialog=BottomSheetDialog(this)
             create.setOnClickListener { 
               createBottomSheetDialog()
              }
    }
 override fun onBackPressed() {
            if (bottomSheetDialog.isShowing){
                bottomSheetDialog.dismiss()
            }
            super.onBackPressed()
        }

     private fun createBottomSheetDialog(){
        bottomSheetDialog.setContentView(R.layout.bottom_sheet_dialog)
        bottomSheetDialog.setCancelable(false)
        bottomSheetDialog.show()

    }
}

I have been tried using this.bottomSheetDialog.dismiss() but not working I also have try dismissing the dialog without if statement and without using super.onBackPressed() but not working.

Upvotes: 1

Views: 1487

Answers (3)

Piotr
Piotr

Reputation: 667

Try setting global variable for activity dialog: BottomSheetDialog? = null

Then in the function for displaying dialog give it a value and show it. Then in onCreate (or whenever you want) just use global variable as a reference eg.:

onBackPressed(){
if(dialog != null){
dialog.dismiss()}}

Upvotes: 0

Md Hanif
Md Hanif

Reputation: 1107

you can simply remove this line from your code

bottomSheetDialog.setCancelable(false)

You can get more details about this here. I guess you need to stop dismiss when clicked anywhere outside the fragment so you can add this :-

bottomSheetDialog.setCanceledOnTouchOutside(false)

It will allow you to dismiss onBackPressed but it won't allow you to dismiss if clicked anywhere outside of your bottom sheet.

Also no need to write this in your Main activity :-

override fun onBackPressed() {
        if (bottomSheetDialog.isShowing){
            bottomSheetDialog.dismiss()
        }
        super.onBackPressed()
    }

Bottom Sheet dialogue will itself dismiss onBackPressed.

Upvotes: 1

Sam Chen
Sam Chen

Reputation: 8857

Try this:

override fun onBackPressed() {
    if (bottomSheetDialog.isShowing){
        bottomSheetDialog.dismiss()
    } else {
        super.onBackPressed()
    }
}

Upvotes: 0

Related Questions