Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 動畫之 TranslateAnimation 應用詳解

編輯:關於 Android 程式設計

Android 中提供了四種基本動畫:AlphaAnimation(透明度)、ScaleAnimation(縮放)、TranslateAnimation(位移)與 RotateAnimation(旋轉)。本文聚焦於 TranslateAnimation(位移動畫)。

TranslateAnimation 相當常用,例如 QQ、網易新聞的菜單條動畫就可以用它來實現。透過以下構造函數即可定義動畫:

TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)

參數說明

  • float fromXDelta:動畫開始的點離當前 View X 坐標上的差值。
  • float toXDelta:動畫結束的點離當前 View X 坐標上的差值。
  • float fromYDelta:動畫開始的點離當前 View Y 坐標上的差值。
  • float toYDelta:動畫結束的點離當前 View Y 坐標上的差值。

常用方法

animation.setDuration(long durationMillis);// 設置動畫持續時間
animation.setRepeatCount(int i);// 設置重複次數
animation.setRepeatMode(Animation.REVERSE);// 設置反方向執行

XML 屬性

android:duration:運行動畫的時間
android:repeatCount:定義動畫重複的時間

程式碼範例

以下範例讓 ImageView 向右位移 150,並反覆執行兩次:

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);
/** 設置位移動畫,向右位移 150 */
final TranslateAnimation animation = new TranslateAnimation(0, 150,0, 0);
animation.setDuration(2000);// 設置動畫持續時間
animation.setRepeatCount(2);// 設置重複次數
animation.setRepeatMode(Animation.REVERSE);// 設置反方向執行
start.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
image.setAnimation(animation);
/** 開始動畫 */
animation.startNow();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/** 結束動畫 */
animation.cancel();
}
});
}
}

效果圖:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved