I have FragmentActivity
and there are 4 fragments inside. LoginFragment, RegistrationFragment, ForgottenPasswordFragment, LocalityFragment
.
User can switch between them by back button, but if you push back button
in default fragment (LoginFragment
or LocalityFragment
) I want to disable it, because it will return user to the SplashScreen
.
So I've found some method how to get currently displayed fragment. I've tried fragment.userVisibleHint
and fragment.isVisible
. Both of them are returning false as I push back button even if that fragment is currently displayed on screen.
Code:
override fun onBackPressed() {
val activeLoginFragment = supportFragmentManager.findFragmentByTag("LOGIN_FRAGMENT") as LoginFragment?
val activeLocalityFragment = supportFragmentManager.findFragmentByTag("LOCALITY_FRAGMENT") as LocalityPickFragment?
createLog("onBackPressedLogin ", activeLoginFragment.toString())
createLog("onBackPressedLogin ", "LoginFragment is: " + activeLoginFragment?.userVisibleHint)
if ( (activeLoginFragment == null || !activeLoginFragment.userVisibleHint) || (activeLocalityFragment == null || !activeLocalityFragment.userVisibleHint) ){
createLog("onBackPressedLogin ", "not visible")
super.onBackPressed()
}
}
fun switchToForgottenPasswordFragment(){
val mPendingRunnable = Runnable {
fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.apply {
replace(R.id.startup_fragment_container, forgottenPasswordFragment)
addToBackStack(null)
commit()
}
}
val fragmentThread = Thread(mPendingRunnable)
fragmentThread.start()
}