Search code examples
androidanimationandroid-animationlayouttransition

Get Animator for LayoutTransition from R.anim XML


I have been searching for a while and can't seem to find anything useful on this topic. Is it possible to set the animation for a LayoutTransition to an animation declared in XML? The default animation will fade the view being added or removed from a ViewGroup and shift the other views accordingly, but I want to have a view slide in or out to the side. I have tried the following to set an Animator from Animation object, but it doesn't seem like it did anything. I just set the fields I found to be common across the two types, but really I have no idea what I am doing with animation.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setLayoutTransition() {
    LayoutTransition transition = new LayoutTransition();

    Animation appearing = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
    Animator aa = transition.getAnimator(LayoutTransition.APPEARING);
    aa.setDuration(appearing.getDuration());
    aa.setInterpolator(appearing.getInterpolator());

    Animation disappearing = AnimationUtils.loadAnimation(context, android.R.anim.slide_out_right);
    Animator bb = transition.getAnimator(LayoutTransition.DISAPPEARING);
    bb.setDuration(disappearing.getDuration());
    bb.setInterpolator(disappearing.getInterpolator());

    transition.setAnimator(LayoutTransition.APPEARING, aa);
    transition.setAnimator(LayoutTransition.DISAPPEARING, bb);

    dashboardLayout.setLayoutTransition(transition);
}

Solution

  • No, you can't. Actually, Animation and Animator are different parts of the API, targeted at slightly different tasks.

    Animators are for value animations, Animations are for view animations. So, an Animator can animate whatever property an object has but you have to specify what and how. Animations are less flexible but have some ready recipes for views.

    So, in your case, you can either define Animators from scratch or manually start Animations on views involved in layout changes -- the latter is possible but I sense it would cause way more hassle than the former.

    Go with Animators, you can easily define them in .xml files too, here's all about it