Search code examples
androidandroid-animationandroid-linearlayout

LinearLayout change android:layoutAnimation programmatically


Is there any way to change android:layoutAnimation to a different animation resource programmatically using Java?


Solution

  • Is there any way to change android:layoutAnimation to a different animation resource programmatically using Java?

    Yes : you can use LayoutAnimationController

    • A layout animation controller is used to animated a layout's, or a view group's, children. Each child uses the same animation but for every one of them, the animation starts at a different time. A layout animation controller is used by ViewGroup to compute the delay by which each child's animation start must be offset

    HERE IS WORKING EXAMPLE CODE

    public class MainActivity extends AppCompatActivity {
    
        LinearLayout rootView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            rootView=findViewById(R.id.rootView);
            LayoutAnimationController anim = AnimationUtils.loadLayoutAnimation(this, R.anim.scale_down);
            rootView.setLayoutAnimation(anim);
        }
    
    
    }
    

    Layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/rootView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <Button
            android:layout_width="match_parent"
            android:id="@+id/buttonPanel"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    R.anim.scale_down

     <layoutAnimation
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/scale_up" />
    

    @anim/scale_up

    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <scale
            android:duration="1000"
            android:fromXScale="0"
            android:fromYScale="0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toXScale="1.0"
            android:toYScale="1.0" />
    </set>