Jetpack导航动画完整侦听器

时间:2019-07-18 09:54:39

标签: android android-jetpack android-jetpack-navigation

当新的导航事件完成以更改状态栏颜色时,我正在尝试使用Jetpack导航库获得回调。

到目前为止,我已经找到 navController.addOnDestinationChangedListener 这会在新导航开始开始但不是完成时通知我,这意味着输入/退出转换已完成。

有什么方法可以知道所有导航转换何时完成?

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
navHostFragment?.childFragmentManager?.addOnBackStackChangedListener {
    val currentFragment = navHostFragment.childFragmentManager.fragments.firstOrNull()
    if (currentFragment is YourFragment) {
        // your code here  
    } 
}

答案 1 :(得分:0)

我遇到了同样的问题,终于找到了解决方法。

这个想法是当当前片段的退出动画结束时,将调用该片段的onDestroyView

只要进入和退出动画的持续时间相同,我们就可以将此方法用作回调。

class BaseFragment() {
    private var leavingDestination = false

    fun navigateNext() {
        leavingDestination = true
        findNavController().navigate(blaBlaBla)
    }

    fun onNavigationAnimationEnds() {
        TODO()
    }

    // We just need to add an extra check, to be sure that onNavigationAnimationEnds is not called on configuration change
    override fun onDestroyView() {
        if(leavingDestination) {
            onNavigationAnimationEnds()
            leavingDestination = false
        }
    }
}

我使用描述的方法在后台/退出片段中调用一些代码。如果您需要导航到的片段中有回调,则可以仅使用共享的ViewModel。像ActivityViewModelNavGraph scoped ViewModel

类似这样的东西:

class FragmentA() {
    private val mainActivityViewModel by activityViewModels<MainActivityViewModel> { viewModelFactory }
    ...
    override fun onDestroyView() {
        if(leavingDestination) {
            mainActivityViewModel.onNavigationAnimationEnds()
            leavingDestination = false
        }
    }
}
...
class MainActivity() {
    private val _navigationAnimationEndsEvent = MutableLiveData(Event())
    val navigationAnimationEndsEvent: LiveData<Event>; get() = _navigationAnimationEndsEvent

    fun onNavigationAnimationEnds() {
        _navigationAnimationEndsEvent.value = Event()
    }
}
...
class FragmentB() {
    private val mainActivityViewModel by activityViewModels<MainActivityViewModel> { viewModelFactory }

    override fun onActivityCreated() {
        ...
        mainActivityViewModel.navigationAnimationEndsEvent.observe(viewLifecycleOwner, Observer {
            it.getContentIfNotHandled()?.let {
                onNavigationAnimationsEnds()
            }    
        })
    }

    private fun onNavigationAnimationEnds() {
        TODO()
    }    
}

我使用的事件类:

open class Event<out T>(private val content: T) {

    var hasBeenHandled = false; private set

    fun getContentIfNotHandled() = if (hasBeenHandled) null else {
        hasBeenHandled = true
        content
    }

    fun peekContent(): T = content
}

P.S .:我尝试覆盖onCreateAnimation / onCreateAnimator函数并向其添加侦听器,但从未调用过它们。