2011-11-15 158 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? –