本例使用TranslateAnimation 給一個ListView的清單項目向下逐步展開(Cascade)的動畫效果,各種基本Animation可以參見Android ApiDemos樣本解析(3): App->Activity->Animation。
本例使用代碼為ListView添加LayoutAnimation.
[java]
AnimationSet set = new AnimationSet(true);
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(50);
set.addAnimation(animation);
animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f,
Animation.RELATIVE_TO_SELF, 0.0f
);
animation.setDuration(2000);
set.addAnimation(animation);
LayoutAnimationController controller
= new LayoutAnimationController(set, 0.5f);
ListView listView = getListView();
listView.setLayoutAnimation(controller);
AnimationSet set = new AnimationSet(true);
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(50);
set.addAnimation(animation);
animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f,
Animation.RELATIVE_TO_SELF, 0.0f
);
animation.setDuration(2000);
set.addAnimation(animation);
LayoutAnimationController controller
= new LayoutAnimationController(set, 0.5f);
ListView listView = getListView();
listView.setLayoutAnimation(controller);
本例Cascade效果是通過TranslateAnimation實現的,本例使用的建構函式:
public TranslateAnimation(int fromXType, float fromXValue, int toXType, float toXValue, int fromYType, float fromYValue, int toYType, float toYValue)
fromXType: 指出fromXValue的模式,本例使用RELATIVE_TO_SELF,表示使用本View的寬度或是高度。RELATIVE_TO_PARENT為父View的寬度或是高度。ABSOLUTE 表示fromXValue使用絕對值。
fromXValue: 起始X座標或當fromXType為RELATIVE_TO_PARENT或是RELATIVE_TO_SELF時表示相對於本View或父View的係數。本例向下展開,在X方向無動畫,因此設為0.
toXType: 指出toXValue的模式,本例使用RELATIVE_TO_SELF,表示使用本View的寬度或是高度。RELATIVE_TO_PARENT為父View的寬度或是高度。ABSOLUTE 表示fromXValue使用絕對值。
toXValue: 結束X座標或當fromXType為RELATIVE_TO_PARENT或是RELATIVE_TO_SELF時表示相對於本View或父View的係數。本例向下展開,在X方向無動畫,因此設為0.
fromYType: 指出fromYValue的模式,本例使用RELATIVE_TO_SELF,表示使用本View的寬度或是高度。RELATIVE_TO_PARENT為父View的寬度或是高度。ABSOLUTE 表示fromYValue使用絕對值。
fromYValue: 起始Y座標或當fromYType為RELATIVE_TO_PARENT或是RELATIVE_TO_SELF時表示相對於本View或父View的係數。
toYType: 指出toYValue的模式,本例使用RELATIVE_TO_SELF,表示使用本View的寬度或是高度。RELATIVE_TO_PARENT為父View的寬度或是高度。ABSOLUTE 表示fromXValue使用絕對值。
toYValue: 結束Y座標或當fromYType為RELATIVE_TO_PARENT或是RELATIVE_TO_SELF時表示相對於本View或父View的係數。本例向下展開,值為1表示向下移動子View的高度。
將動畫時間從100改成2000可以較慢的速度顯示動畫效果。