Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

July 08, 2021

Click again to exit the app in navigation component [kotlin]

July 08, 2021 Posted by Piash , No comments
 class MainActivity : BaseActivity() {  
   private lateinit var navController: NavController  
   private lateinit var navHostFragment: NavHostFragment  
   private var doubleBackToExitPressedOnce = false
 override fun onCreate(savedInstanceState: Bundle?) {  
     super.onCreate(savedInstanceState)  
     binding = ActivityMainBinding.inflate(layoutInflater)  
     setContentView(binding.root)  
  navHostFragment =  
       supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment  
     navController = navHostFragment.navController  
   }  
 override fun onBackPressed() {  
     if (navHostFragment.childFragmentManager.backStackEntryCount > 0) {  
       super.onBackPressed()  
     } else {  
       if (doubleBackToExitPressedOnce) {  
         finish()  
         return  
       }  
       this.doubleBackToExitPressedOnce = true  
       showToast("Click again to Exit")  
       Handler().postDelayed(  
         { doubleBackToExitPressedOnce = false },  
         2000  
       )  
     }  
   }  
 }  

0 comments:

Post a Comment