代码之家  ›  专栏  ›  技术社区  ›  Martin

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

  •  0
  • Martin  · 技术社区  · 6 年前

    我有 FragmentActivity 里面有4块碎片。 LoginFragment, RegistrationFragment, ForgottenPasswordFragment, LocalityFragment .

    back button 在默认片段中( LoginFragment LocalityFragment SplashScreen .

    所以我找到了一些方法来获取当前显示的片段。我试过了 fragment.userVisibleHint fragment.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 回复  |  直到 6 年前