buptcoder
buptcoder

Reputation: 2702

Translation and scale layout Animation Problem in Android

I have the view with layout below.

enter image description here

What I want is moving View B to the position of View A and at the same time move RelativeLayout C up with the same height of View B. The two actions will be done with the animations. Like the picture shown below.

enter image description here

I am using ObjectAnimation to implement this feature, but when I am using the

    float viewBY = viewB.getTranslationY();
    ObjectAnimator viewBMoveUp
                = ObjectAnimator.ofFloat(viewB, "translationY",
                viewBY, viewBY - viewB.getHeight());

    float layoutCCurrentY = layoutC.getY();
    ObjectAnimator layoutCMoveUp
            = ObjectAnimator.ofFloat(layoutC, "Y",
            layoutCCurrentY, layoutCCurrentY - viewB.getHeight());
    AnimatorSet animSet = new AnimatorSet();
        animSet.play(viewBMoveUp).with(layoutCMoveUp);
        animSet.setDuration(150);
        animSet.start();

I find the LayoutC's bottom is also up with viewB.getHeight(), which is not I expected. Like the picture below:

enter image description here

So anybody can help about this?

Upvotes: 1

Views: 199

Answers (1)

Michael Udjiawan
Michael Udjiawan

Reputation: 258

One simpler way to achieve the expected result is to use animateLayoutChanges attribute in the parent layout.

<!-- Defines whether changes in layout (caused by adding and removing items) should cause 
a LayoutTransition to run. When this flag is set to true, a default LayoutTransition object 
will be set on the ViewGroup container and default animations will run when these layout 
changes occur.-->
<attr name="animateLayoutChanges" format="boolean" />

With this, you don't need to manually animate each movement. When you set viewA visibility to View.GONE, the parent layout will fade out viewA and translate position of viewB and layoutC.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true">

    <View
        android:id="@+id/viewA"
        android:layout_width="match_parent"
        android:layout_height="60dp" />

    <View
        android:id="@+id/viewB"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_below="@+id/viewA" />

    <RelativeLayout
        android:id="@+id/layoutC"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/viewB"
        android:layout_alignParentBottom="true">

    </RelativeLayout>

</RelativeLayout>

Upvotes: 2

Related Questions