代碼設置Dialog的進入和退出動畫

因項目對外發布的是JAR包,不能有資源文件,因此所有的界面和動畫都不方便通過xml去寫,都需要通過JAVA代碼去生成。

進入動畫的設置
重寫Dialog的show()方法,getContentView()和getAnimation()需自定義,就是這麼簡單。

 @Override
    public void show() {
        mContentView = getContentView();
        setContentView(mContentView);
        setCancelable(false);
        super.show();
        if (mContentView != null) {
            mContentView.startAnimation(getAnimation());
        }
    }
      @Override
    public Animation getAnimation() {
        AnimationSet set = new AnimationSet(true);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
        //ScaleAnimation scaleAnimation = new ScaleAnimation(0,1f,0,1f,
        //      Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        set.addAnimation(alphaAnimation);
        //  set.addAnimation(scaleAnimation);
        set.setDuration(500);
        return set;
    }

退出動畫的設置
退出時的動畫寫法有點不一樣,需要加一個listener如下:

  @Override
    public void dismiss() {

        if (mContentView != null){
            mContentView.startAnimation(getExitAnimation());
        }
         super.dismiss();
     }
      private Animation getExitAnimation() {
        AnimationSet set = new AnimationSet(true);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        set.addAnimation(alphaAnimation);
        set.setFillAfter(true);
        set.setDuration(500);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }
            @Override
            public void onAnimationEnd(Animation animation) {
                if (mContentView != null){
                //用view的post()方法不會報錯,直接用super.dismiss()會報錯的,你可以試試。
                    mContentView.post(new Runnable() {
                        @Override
                        public void run() {
                            UnsubscribeConfirmDialog.super.dismiss();
                        }
                    });
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        return  set;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章