Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Animation 動畫實作 Android 應用歡迎頁,不必開線程

網路上看到的 Android 歡迎頁動輒開一條背景線程計時,再 Handler 跳頁,寫起來囉嗦又容易出錯。其實如果只是「淡入 → 停留 → 跳轉」這種效果,交給 Animation 加上監聽器就足夠了,一行線程都不用寫。

做法概述

在歡迎頁的版面裡放一張 ImageView,載入一個 alpha 淡入動畫,並為這個動畫掛上監聽器。當 onAnimationEnd 被觸發時,就 startActivity 跳到主介面並 finish() 掉自己。整個流程完全由動畫的播放週期驅動,時機精準、程式碼極短。

關鍵設定

  • setFillEnabled(true) 與 setFillAfter(true):讓動畫停在最後一幀,避免圖片在跳頁前突然「跳回」初始狀態。
  • setAnimationListener(this):讓 Activity 本身實作 AnimationListener。
  • 在 onKeyDown 攔下 BACK 鍵,避免使用者一按就回到桌面、後續 finish() 又產生非預期的堆疊行為。

完整程式碼

/**
 * 歡迎界面
 * @author 小建楓葉
 */
public class WelcomeActivity extends Activity implements AnimationListener {

    private ImageView  imageView       = null;
    private Animation  alphaAnimation  = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);

        imageView = (ImageView) findViewById(R.id.welcome_image_view);
        alphaAnimation = AnimationUtils.loadAnimation(this, R.anim.welcome_alpha);
        alphaAnimation.setFillEnabled(true);   // 啟動 Fill 保持
        alphaAnimation.setFillAfter(true);     // 動畫最後一幀停留在 View 上
        imageView.setAnimation(alphaAnimation);

        alphaAnimation.setAnimationListener(this);   // 為動畫設置監聽
    }

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) {
        // 動畫結束時結束歡迎界面並轉到主界面
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 在歡迎界面屏蔽 BACK 鍵
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return false;
    }
}

動畫檔放在 res/anim/welcome_alpha.xml,用 alpha 標籤描述 fromAlpha、toAlpha 與 duration 即可;想改成位移或縮放開場,只要換成 translate 或 scale,Activity 這邊完全不必修改。

Copyright © Linux教程網 All Rights Reserved