How does one Animate Layout properties of ViewGroups?

后端 未结 3 1166
别那么骄傲
别那么骄傲 2020-12-15 01:07

I have the following layout:




        
3条回答
  •  误落风尘
    2020-12-15 01:34

    A different way to the solution posted by @knickedi is to use ObjectAnimator instead of Runnable. The idea is to use ObjectAnimator to adjust the weight of both left and right views. The views, however, need to be customised so that the weight can be exposed as a property for the ObjectAnimator to animate.

    So first, define a customised view (using a LinearLayout as an example):

    public class CustomLinearLayout extends LinearLayout {
        public CustomLinearLayout(Context context) {
            super(context);
        }
    
        public CustomLinearLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public void setMyWeight(float value) {
            LinearLayout.LayoutParams p = (LinearLayout.LayoutParams)getLayoutParams();
            p.weight = value;
            requestLayout();
        }
    }
    

    Then, update the layout XML to use this custom linear layout.

    Then, when you need to toggle the animation, use ObjectAnimator:

    ObjectAnimator rightView = ObjectAnimator.ofFloat(viewgroup_right, "MyWeight", 0.5f, 1.0f);
    ObjectAnimator leftView = ObjectAnimator.ofFloat(viewgroup_left, "MyWeight", 0.5f, 0.0f);
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.setDuration(1000); // 1 second of animation
    animatorSet.playTogether(rightView, leftView);
    animatorSet.start();
    

    The above code assumes both views are linear layout and are half in weight to start with. The animation will expand the right view to full weight (so the left one is hidden). Note that ObjectAnimator is animated using the "MyWeight" property of the customised linear layout. The AnimatorSet is used to tie both left and right ObjectAnimators together, so the animation looks smooth.

    This approach reduces the need to write runnable code and the weight calculation inside it, but it needs a customised class to be defined.

提交回复
热议问题