Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyway to programmatically animate layout weight property of linear layout

Tags:

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?

like image 247
2cupsOfTech Avatar asked Jul 16 '12 14:07

2cupsOfTech


People also ask

What is layout weight linear layout?

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.

How do you move a button in linear layout?

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.


1 Answers

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(); 
like image 194
kostya17 Avatar answered Sep 18 '22 18:09

kostya17