简体   繁体   中英

Android Navigation Component with Retained Fragments and enter animation

I am trying to use the Navigation Component with a retained Fragment and an enter animation. The fragment appears with the animation as expected. On rotating my device I get the following crash:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

I can solve this by removing the enter animation (from the nav graph) or by making the fragment not be retained.

Does anyone have a clue how to solves this as I wanted both retained and the animation.

Here is my onCreate:

private var binding: FragmentDemoBinding? = null

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? {

    if (binding == null) {
        binding = FragmentDemoBinding.inflate(inflater, container, false)
    }

    retainInstance = true
    return binding?.root
}

edit : Actually on reading a bit more I am not sure it makes sense to try and use retained fragments within the navigation component. If I need to persist data on configuration changes I guess a headless fragment or use onSaveInstance or ViewModel component etc.

In onDestroyView method remove all views or just animation view.

override fun onDestroyView() {
if(view != null){
val parent = view.parent
parent.removeAllViews
}
super.onDestroyView()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM