Anyway to programmatically animate layout weight property of linear layout

前端 未结 5 1752
暗喜
暗喜 2021-02-18 15:12

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 v

5条回答
  •  生来不讨喜
    2021-02-18 16:00

    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();
    

提交回复
热议问题