how to handle back pressed in Kotlin

2020-04-08 14:00发布

问题:

my app having only two base activity and several fragment,, i want to display an Exit alert when user reach particular base fragment by clicking back press

override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
          drawer_layout.closeDrawer(GravityCompat.START)

        } else {
         // super.onBackPressed()
            AlertDialog.Builder(this)
                .setTitle("Exit Alert")
                .setMessage("Do You Want To Exit Petals App?")
                .setPositiveButton(android.R.string.ok) { dialog, whichButton ->
                    super.onBackPressed()
                }
                .setNegativeButton(android.R.string.cancel) { dialog, whichButton ->

                }
                .show()

        } 

i used addtosatck on each fragment

回答1:

At first Check Visible Fragment

val currentFragment =this@ActivityName.supportFragmentManager.findFragmentById(R.id.Your_id)
        if(currentFragment is FragmentName)
        {
         // AlertDialog()
        }

Finally

override fun onBackPressed() 
{
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
          drawer_layout.closeDrawer(GravityCompat.START)

        } else 
        {

            val currentFragment =this@ActivityName.supportFragmentManager.findFragmentById(R.id.Your_id)
            if(currentFragment is SpecificFragmentName)
            {
               AlertDialog.Builder(this@ActivityName)
                    .setTitle("Exit Alert")
                    .setMessage("Do You Want To Exit Petals App?")
                    .setPositiveButton(android.R.string.ok) { dialog, whichButton ->
                        super.onBackPressed()
                    }
                    .setNegativeButton(android.R.string.cancel) { dialog, whichButton ->

                    }
                    .show()
            }
            else{
            super.onBackPressed()
            }


    }
}


回答2:

You can just:

    val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
    }

For more information you can check this.