简体   繁体   中英

how can i press back just to close the app?

I implemented this function in the mainActivity of my app to ask to press back twice to exit the application, everything works but it asks me to double back press even when I want to close a fragment, how can I limit it only to the main screen?

override fun onBackPressed() {
        if (backPressedTime + 2000 > System.currentTimeMillis()) {
            super.onBackPressed()
        }else{
            Toast.makeText(this, "Premere ancora per tornare indietro", Toast.LENGTH_SHORT).show()
        }
        backPressedTime = System.currentTimeMillis()
    }

You have to use the OnBackPressedCallBack Interface which will provide a function named handleOnBackPressed() that is called when you click navigate back button. If your app is a Single Activity App, then you have to call finish() function that will finish your activity and this will lead to exit from the app. You can reach finish() by using requireActivity() in the specific fragment. If you are using Navigation Component, try to put this function in your First Destination Fragment:

    private fun setOnBackButtonClickListener() {
    val onBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
               if (backPressedTime + 2000 > System.currentTimeMillis()) {
                    requireActivity.finish()
               } else {
                    Toast.makeText(this, "Premere ancora per tornare indietro", 
                    Toast.LENGTH_SHORT).show()
               }
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
}

and if you are not using Navigation Component, try to use the same function in the fragment you want to end the app from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM