1

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Shashank Pandey
  • 683
  • 6
  • 14

3 Answers3

1

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.

WhiteSpidy.
  • 1,107
  • 1
  • 6
  • 28
0

Try this:

override fun onBackPressed() {
    if (bottomSheetDialog.isShowing){
        bottomSheetDialog.dismiss()
    } else {
        super.onBackPressed()
    }
}
Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • @Shashank Pandey You can write a Log to check if `onBackPressed()` actually gets called when you press the back button, then check the `isShowing()` value to make sure it is true, step by step to narrow down the problem source. – Sam Chen Dec 10 '20 at 05:47
0

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()}}
Piotr
  • 545
  • 4
  • 13