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?
LinearLayout also supports assigning a weight to individual children with the android:layout_weight attribute. This attribute assigns an "importance" value to a view in terms of how much space it should occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent view.
You can set the android:layout_weight='1' and both buttons will share the screen equally(side by side) or if you want the extra space between them, you can place a button each in a linear layout and set the android:layout_gravity to left and right for each.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With