android中提供了4中動(dòng)畫:
AlphaAnimation 透明度動(dòng)畫效果
ScaleAnimation 縮放動(dòng)畫效果
TranslateAnimation 位移動(dòng)畫效果
RotateAnimation 旋轉(zhuǎn)動(dòng)畫效果
本節(jié)講解TranslateAnimation動(dòng)畫,TranslateAnimation比較常用,比如QQ,網(wǎng)易新聞菜單條的動(dòng)畫,就可以用TranslateAnimation實(shí)現(xiàn),
通過(guò)TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) 來(lái)定義動(dòng)畫
參數(shù)說(shuō)明:
復(fù)制代碼 代碼如下:
float fromXDelta 動(dòng)畫開始的點(diǎn)離當(dāng)前View X坐標(biāo)上的差值
float toXDelta 動(dòng)畫結(jié)束的點(diǎn)離當(dāng)前View X坐標(biāo)上的差值
float fromYDelta 動(dòng)畫開始的點(diǎn)離當(dāng)前View Y坐標(biāo)上的差值
float toYDelta 動(dòng)畫開始的點(diǎn)離當(dāng)前View Y坐標(biāo)上的差值
常用方法:
復(fù)制代碼 代碼如下:
animation.setDuration(long durationMillis);//設(shè)置動(dòng)畫持續(xù)時(shí)間
animation.setRepeatCount(int i);//設(shè)置重復(fù)次數(shù)
animation.setRepeatMode(Animation.REVERSE);//設(shè)置反方向執(zhí)行
Xml屬性:
復(fù)制代碼 代碼如下:
android:duration:運(yùn)行動(dòng)畫的時(shí)間
android:repeatCount:定義動(dòng)畫重復(fù)的時(shí)間
代碼:
復(fù)制代碼 代碼如下:
public class MainActivity extends Activity {
ImageView image;
Button start;
Button cancel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.main_img);
start = (Button) findViewById(R.id.main_start);
cancel = (Button) findViewById(R.id.main_cancel);
/** 設(shè)置位移動(dòng)畫 向右位移150 */
final TranslateAnimation animation = new TranslateAnimation(0, 150,0, 0);
animation.setDuration(2000);//設(shè)置動(dòng)畫持續(xù)時(shí)間
animation.setRepeatCount(2);//設(shè)置重復(fù)次數(shù)
animation.setRepeatMode(Animation.REVERSE);//設(shè)置反方向執(zhí)行
start.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
image.setAnimation(animation);
/** 開始動(dòng)畫 */
animation.startNow();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/** 結(jié)束動(dòng)畫 */
animation.cancel();
}
});
}
}
效果: