Learn MotionLayout step by step — Part 2 : <ConstraintSet>,<Constaint>, <OnClick>, clickAction

ömer iyiöz
DigiGeek
Published in
2 min readMar 4, 2021

At the end this article, you will understand the use of the following in scene file :

  • <ConstraintSet> and <Constaint>
  • <OnClick> inside <Transition>.
  • clickAction attribute of <OnClick>

Example 3 :

When textView is clicked, position of textView changes from top,left to bottom right and vice versa gradually.

Below is the codes of our 3rd example.

Let me explain the below code, firstly.

<OnClick
app:clickAction="toggle"
app:targetId="@id/textView3" />
  • At the first click on textView3 , the animation plays from start to end.
  • If we click textView3 again, the animation plays from end to start.
  • If we click textView3 again, the animation plays from start to end.
  • If we click textView3 again, the animation plays from end to start.
  • and so on …

It’s the result of toggle clickAction.

MotionScene file contains two ConstraintSet,

  • one for applying at the start of animation,
  • one for applying at the end of animation.

At the start of animation, the constraints inside start constraintSet is applied. Thus textView3 is at the top left of its parent.

At the end of animation, the constraints inside end constraintSet is applied. Thus textView3 is at the bottom right of its parent.

Example 4 :

By swiping, the position of 3 imageViews change gradually.

Below is the codes of our 4th example :

OnSwipe

<OnSwipe app:touchAnchorId="@id/imageViewRun" />

swiping starts the animation. While swiping, the anchored view is imageRun, which means imageViewRun tracks your finger position. In other words, imageViewRun moves as you swipe but the distance between the imageViewRun and your swiping finger remains unchanged while swiping.

touchAnchorId

When you touch any point inside the MotionLayout screen, and move your finger, imageViewRun tracks your finger position. MotionLayout will keep imageViewRun the same distance from the finger that’s swiping.

For example, when you move your finger -100pixel in y coordinate, then the y coordinate of imageViewRun changes -100pixel.

I shared the examples in the following github repo. Feel free to contribute.

Happy Coding !

--

--