Skip to content

miguelhincapie/NestedMotionLayout

Repository files navigation

NestedMotionLayout

License

An easy workaround to use MotionLayout with nested children in XML



"MotionLayout works only with its direct children. It does not support nested layout hierarchies or activity transitions."

Welp, a beautiful app usually has complex XML hierarchies, so keeping all the UI things as direct child is kinda impossible, so with few easy lines of code I made it works as you can see:



This is how Activity XML hierarchy looks like


The magic

As you can see in above XML, there are three scenes: activity_main_scene, header_container_scene, child_header_container_scene. Each one will take care about its direct children and the only missing thing is synch them up:

  1. Implement MotionLayout.TransitionListener in your Activity, Fragment or independent class.
  2. Create the scenes you need (in the example I have 3)
  3. set up the transaction listener for each one (call this fun in onCreate, onViewCreated or something like that):
private fun setUpMotionLayoutListener() = with(binding) {
        rootContainer.setTransitionListener(this@MainActivity)
        headerContainer.setTransitionListener(this@MainActivity)
        childHeaderContainer.setTransitionListener(this@MainActivity)
    }
  1. synchronise them using following code:
private fun updateNestedMotionLayout(motionLayout: MotionLayout?) = motionLayout?.let {
        with(binding) {
            if (it.id == rootContainer.id) {
                headerContainer.progress = it.progress
                childHeaderContainer.progress = it.progress
            }
        }
    }

And that's all!

Stackoverflow questions

If this help you in any way, please vote up some stackoverflow's answers related to this:
Answer one
Answer two

About me

Stackoverflow Developer Story

profile for MiguelHincapieC at Stack Overflow, Q&A for professional and enthusiast programmers



About

Workaround to use MotionLayout with nested children in XML

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages