2011-11-15 91 views
38

我想在我的活动中调整一些布局的大小。以编程方式调整布局的大小(作为动画)

下面是主要的XML代码:

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" 
    android:orientation="vertical" > 

    <LinearLayout 
     android:id="@+id/top" 
     android:layout_width="fill_parent" 
     android:layout_height="0dip" 
     android:layout_weight="1" 
     android:background="#3ee3e3" > 
    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/middle" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_weight="1"> 
    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/bottom" 
     android:layout_width="fill_parent" 
     android:layout_height="0dip" 
     android:layout_weight="1" 
     android:background="#fe51e6" > 
    </LinearLayout> 
</LinearLayout> 

正如你可以看到,顶部和底部的布局高度的是0,中间 布局覆盖了所有的地方。

我想以编程方式减少中间布局大小,同时增加顶部 和底部布局大小,直到所有布局具有相同的高度。

我希望它看起来像动画。

我该怎么做?

谢谢

回答

91

我为类似的目的写了一个ResizeAnimation。这很简单但很昂贵。

/** 
* an animation for resizing the view. 
*/ 
public class ResizeAnimation extends Animation { 
    private View mView; 
    private float mToHeight; 
    private float mFromHeight; 

    private float mToWidth; 
    private float mFromWidth; 

    public ResizeAnimation(View v, float fromWidth, float fromHeight, float toWidth, float toHeight) { 
     mToHeight = toHeight; 
     mToWidth = toWidth; 
     mFromHeight = fromHeight; 
     mFromWidth = fromWidth; 
     mView = v; 
     setDuration(300); 
    } 

    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) { 
     float height = 
       (mToHeight - mFromHeight) * interpolatedTime + mFromHeight; 
     float width = (mToWidth - mFromWidth) * interpolatedTime + mFromWidth; 
     LayoutParams p = mView.getLayoutParams(); 
     p.height = (int) height; 
     p.width = (int) width; 
     mView.requestLayout(); 
    } 
} 
+1

我认为这是一个很棒的[解决方案](http://stackoverflow.com/a/13381228/1276636)。 – Sufian

+1

我想你也需要重写'public void initialize'&'public boolean willChangeBounds'。 –

+0

非常感谢! –

4

的Honeycomb(Android 3.0的)存在AnimatorObjectAnimator类平滑的动画。

读它here

如何与反弹插动画的图组(的LinearLayout)的移动为例。

BounceInterpolator bounceInterpolator = new BounceInterpolator(); 
ObjectAnimator anim = ObjectAnimator.ofFloat(myViewGroup, "translationY", 0f, -200); 
anim.setInterpolator(bounceInterpolator); 
anim.setDuration(1100).start(); 

这将触发一个具有反弹效果的平滑动画,并真正移动视图,而不像Honeycomb之前的动画。从文档:

以前的动画改变了目标对象的视觉外观......但它们实际上并没有改变对象本身。

+1

你可以发布一些代码示例或更多的信息对这些对象@ddcoy? –