Anyway to programmatically animate layout weight property of linear layout

Viewed 9513

I have two views in a linear layout, I programmatically change their layout_weight property. Is there a way I could animate this change in weight so when the weight is changed views slides towards a new size?

5 Answers

Note: I am not sure that this is the best way, but I tried it and it's working fine

Simply using ValueAnimator

ValueAnimator m1 = ValueAnimator.ofFloat(0.2f, 0.5f); //fromWeight, toWeight
m1.setDuration(400);
m1.setStartDelay(100); //Optional Delay
m1.setInterpolator(new LinearInterpolator());
m1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
         @Override
         public void onAnimationUpdate(ValueAnimator animation) {
             ((LinearLayout.LayoutParams) viewToAnimate.getLayoutParams()).weight = (float) animation.getAnimatedValue();
             viewToAnimate.requestLayout();
         }

});
m1.start();

More About ValueAnimator

Another way is to use old Animation class, as described in https://stackoverflow.com/a/20334557/2914140. In this case you can simultaneously change weights of several Views.

private static class ExpandAnimation extends Animation {
    private final View[] views;
    private final float startWeight;
    private final float deltaWeight;

    ExpandAnimation(View[] views, float startWeight, float endWeight) {
        this.views = views;
        this.startWeight = startWeight;
        this.deltaWeight = endWeight - startWeight;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        float weight = startWeight + (deltaWeight * interpolatedTime);
        for (View view : views) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) view.getLayoutParams();
            lp.weight = weight;
            view.setLayoutParams(lp);
        }
        views[0].getParent().requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

All of the answers above weren't working for me (they would simply "snap" and not animate), but after I added weight_sum="1" to the parent layout, it started working. Just in case someone else comes up with the same issue.

Related