Anyway to programmatically animate layout weight property of linear layout

2cupsOfTech picture 2cupsOfTech · Jul 16, 2012 · Viewed 8.9k times · Source

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?

Answer

kostya17 picture kostya17 · Dec 4, 2015

You can simply use ObjectAnimator.

ObjectAnimator anim = ObjectAnimator.ofFloat(
                viewToAnimate,
                "weight",
                startValue,
                endValue);
        anim.setDuration(2500);
        anim.start();

The one problem is that View class has no setWeight() method (which is required by ObjectAnimator). To address this I wrote simple wrapper which helps archive view weight animation.

public class ViewWeightAnimationWrapper {
    private View view;

    public ViewWeightAnimationWrapper(View view) {
        if (view.getLayoutParams() instanceof LinearLayout.LayoutParams) {
            this.view = view;
        } else {
            throw new IllegalArgumentException("The view should have LinearLayout as parent");
        }
    }

    public void setWeight(float weight) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.weight = weight;
        view.getParent().requestLayout();
    }

    public float getWeight() {
        return ((LinearLayout.LayoutParams) view.getLayoutParams()).weight;
    }
}

Use it in this way:

    ViewWeightAnimationWrapper animationWrapper = new ViewWeightAnimationWrapper(view);
    ObjectAnimator anim = ObjectAnimator.ofFloat(animationWrapper,
                    "weight",
                    animationWrapper.getWeight(),
                    weight);
            anim.setDuration(2500);
            anim.start();