Thursday, April 7, 2016

Expand collapse a layout height with animation

Sometimes according to requirement you need that the view will animate when you change its height or width.
There are multiple ways to set width and height with animation.I have  mention one of them,which is small and easy enough to understand.


In this i have used ValueAnimator :

Class Overview


This class provides a simple timing engine for running animations which calculate animated values and set them on target objects.
There is a single timing pulse that all animations use. It runs in a custom handler to ensure that property changes happen on the UI thread.
By default, ValueAnimator uses non-linear time interpolation, via the AccelerateDecelerateInterpolator class, which accelerates into and decelerates out of an animation. This behavior can be changed by calling setInterpolator(TimeInterpolator).


Animators can be created from either code or resource files.
Here is an example of a ValueAnimator resource file:

<animator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:valueFrom="1"
    android:valueTo="0"
    android:valueType="floatType"
    android:repeatCount="1"
    android:repeatMode="reverse"/>
 

Code to change size of an view with animation programatically :

 
public static void collapse_expand(final View v, int duration, int targetHeight)
{
    int prevHeight  = v.getWidth(); 
 ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight); 
 valueAnimator.setInterpolator(new DecelerateInterpolator());     
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() 
{
        @Override         
      public void onAnimationUpdate(ValueAnimator animation) 
      {
         //you can change width or height according to your need.
            v.getLayoutParams().width = (int) animation.getAnimatedValue(); 
            v.requestLayout(); 
       }

    }); 
 valueAnimator.setInterpolator(new DecelerateInterpolator());     
 valueAnimator.setDuration(duration); 
 valueAnimator.start();}


Usage :
             //view   //duration    //size
collapse_expand(view,    2000,      500); 


If size if greater than of last known size then view will expand,
and if size is smaller ,then  view will collapse.


This is most easy and smallest way to do so,....

Enjoy..!



0 comments:

Post a Comment

Don't lose faith when you see others receive answers to their prayers

An elephant and a dog became pregnant at same time. Three months down the line the dog gave birth to six puppies. Six months later the dog...

 

G-Expo Template by Ipietoon Cute Blog Design