Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle back pressed in Kotlin

Tags:

android

kotlin

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

like image 475
m.karman Avatar asked Jul 10 '19 07:07

m.karman


People also ask

How do you handle back buttons?

This example demonstrates how do I handle back button in an android activity. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I disable back press in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }


1 Answers

At first Check Visible Fragment

val currentFragment [email protected](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 [email protected](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()
            }


    }
}
like image 61
IntelliJ Amiya Avatar answered Oct 24 '22 00:10

IntelliJ Amiya