androidanimationobjectanimator

How to move child view independently to parent view?


I am new to Android Studio and I encountered a problem.

So I have three buttons contained in a layout. What I want to do is move one button, lets call it button1, upwards to position (x,y) when this button is clicked and whole (layout without button1) downwards, out of the screen with button1 staying in position (x,y), some sort of button push effect

I used objectAnimator. Firstly I moved button1 upwards, which worked as expected, but as soon as I tried to move whole layout downwards, the button1 moves downwards with the whole layout, which I do not want, I want it to stay at position (x,y) for a while and then move downwards and out of the screen. Is it possible to use objectAnimator independently so button1 animation is not dependent on the whole layout

So this is a simplified XML file

 <RelativeLayout 
   android:height="600dp"
   android:width="800dp">

   <Button 
   android:id="@+id/button1/>
   <Button 
   android:id="@+id/button2/>
   <Button 
   android:id="@+id/button3/>

</RelativeLayout>

And this is what I tried in java

ObjectAnimator objAnimUp = ObjectAnimator.ofFloat(button1, "y", -600);
ObjectAnimator objAnimDown = ObjectAnimator.ofFloat(button2, "y", 1000);

objAnimUp.setDuration(500);
objAnimDown.setDuration(1000);

objAnimUp.start();
objAnimDown.start();

Code above translates button1 upwards, and then the whole layout downwards, including button1 (which is part of the layout). I do not want that. I want that button1 stays at new position and after a while move downwards Is it possible to remove button1 temporarily from layout and move it upwards independently?

I tried "button1.removeParent()" but that does not seem to make a difference. Are there any other solutions?

Thank you for your answers


Solution

  • Basically, you can't move if the button is in same parent layout. You have to add one more parent layout which will hold the button and other view which you want to animate down. Try this,

     <RelativeLayout 
           android:height="match_parent"
           android:width="match_parent">
        <RelativeLayout 
           android:height="600dp"
           android:width="800dp">
    
           <Button 
           android:id="@+id/button2/>
           <Button 
           android:id="@+id/button3/>
    
        </RelativeLayout>
        <Button 
           android:id="@+id/button1/>
        </RelativeLayout>
    

    Now apply the same animation it will work the button which is outside is the one you want to move up.