Search code examples
androidandroid-relativelayouttranslate-animation

Animation doesn't work when attached to the parent (RelativeLayout)layout?


I tried to animate the button from top to a fixed position on the screen, it worked, when clicklistener was added on the button, but it doesn't get worked while attached to the relativelayout. So that the button including relativelayout get animated. I think the problem is when attaching layouts within nested viewgroups, Please help me with a solution. Thanks in advance.

 b = (Button) findViewById(R.id.simpleButton);
    relativeLayout = (RelativeLayout) findViewById(R.id.wrapper);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            b.startAnimation(animations());
        }
    });
    relativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            relativeLayout.setAnimation(animations());
        }
    });
}


private TranslateAnimation animations() {
    TranslateAnimation translateAnimation = new TranslateAnimation(0f, 0f, 0, -40);
    translateAnimation.setDuration(1000);
    translateAnimation.setInterpolator(new AccelerateInterpolator());
    return translateAnimation;
}

Here is the XML;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
     <RelativeLayout
android:id="@+id/wrapper"
android:layout_width="match_parent"
android:background="#cbcbbc"
android:layout_height="60dp">
    <Button
        android:id="@+id/simpleButton"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="Go next page" />
   </RelativeLayout>

   </LinearLayout>

Solution

  • Add this to RelativeLayout:

    android:clickable="true"
    

    Instead of:

    relativeLayout.setAnimation(animations());
    

    Do this:

    relativeLayout.startAnimation(animations());