如何检查fragmentActivity中的片段是否可见?

时间:2018-10-27 10:27:32

标签: android android-fragments kotlin

我有FragmentActivity,里面有4个片段。 LoginFragment, RegistrationFragment, ForgottenPasswordFragment, LocalityFragment

用户可以通过“后退”按钮在它们之间切换,但是如果您在默认片段(back buttonLoginFragment)中按LocalityFragment,则想禁用它,因为它将使用户返回到SplashScreen

因此,我找到了一些方法来获取当前显示的片段。我已经尝试过fragment.userVisibleHintfragment.isVisible。即使我当前在屏幕上显示该片段,当我按下按钮时,它们都将返回false。

代码:

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()
    }

0 个答案:

没有答案