From aad5f3344bb71864125cd05e5a725cf58a8a2fb2 Mon Sep 17 00:00:00 2001 From: Mahmoud Maghrabia Date: Sat, 16 Dec 2023 16:35:26 +0200 Subject: [PATCH] fix navigation by not opening already opened screens --- .../islamey/hamza/wazaker/ui/MainActivity.kt | 35 +++++++++++++------ 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/islamey/hamza/wazaker/ui/MainActivity.kt b/app/src/main/java/com/islamey/hamza/wazaker/ui/MainActivity.kt index bddde12..e08aa88 100644 --- a/app/src/main/java/com/islamey/hamza/wazaker/ui/MainActivity.kt +++ b/app/src/main/java/com/islamey/hamza/wazaker/ui/MainActivity.kt @@ -20,7 +20,13 @@ import dagger.hilt.android.AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding - lateinit var navController: NavController + private val navController: NavController by lazy { + val navHostFragment = + supportFragmentManager.findFragmentById(R.id.hostFragment) as NavHostFragment + navHostFragment.navController + } + + private var lastOpenedScreenId = R.id.home_action override fun onCreate(savedInstanceState: Bundle?) { installSplashScreen() @@ -42,30 +48,32 @@ class MainActivity : AppCompatActivity() { } private fun setUpBottomViewNavigation() { - val navHostFragment = - supportFragmentManager.findFragmentById(R.id.hostFragment) as NavHostFragment - navController = navHostFragment.navController - binding.bottomNavigationView.setOnItemSelectedListener { menuItem -> when (menuItem.itemId) { - R.id.home_action -> { - navController.navigate(R.id.homeFragment) + doIfNotCurrent(R.id.home_action){ + navController.navigate(R.id.homeFragment) + } true } R.id.qibla_action -> { openQiblaActivity() - true + // as we open another activity we should not lose current selection + false } R.id.forty_action -> { - navController.navigate(R.id.fortyHadithListFragment) + doIfNotCurrent(R.id.forty_action){ + navController.navigate(R.id.fortyHadithListFragment) + } true } R.id.settings_action -> { - navController.navigate(R.id.settingsFragment) + doIfNotCurrent(R.id.settings_action){ + navController.navigate(R.id.settingsFragment) + } true } @@ -74,6 +82,13 @@ class MainActivity : AppCompatActivity() { } } + private fun doIfNotCurrent(actionId: Int, action : ()-> Unit) { + if (actionId != lastOpenedScreenId){ + action.invoke() + lastOpenedScreenId = actionId + } + } + private fun openQiblaActivity() { val intent = Intent(this, CompassActivity::class.java) intent.putExtra(Constants.TOOLBAR_BG_COLOR, "#FFFFFF") // Toolbar Background color