2011-08-15 145 views
1

我想向我的應用程序添加一個動畫,該動畫將隱藏或顯示單擊一個菜單。基本上類似於Pulse新聞閱讀器文章視圖。我可以爲菜單容器設置動畫。但是,菜單不會在主容器爲菜單持有者創建空間的同時滑下。我想知道如何解決這個問題。Android動畫:隱藏/顯示菜單

這裏是我的動畫代碼:

if(homeTabBar.getVisibility() == View.GONE){ 
    homeTabBar.setVisibility(View.VISIBLE); 
    final Animation tabBlockHolderAnimation = AnimationUtils.loadAnimation(ArticleActivity.this, R.anim.tab_down); 

    tabBlockHolderAnimation.setFillAfter(true); 
    homeTabBar.startAnimation(tabBlockHolderAnimation); 


}else{ 

    final Animation tabBlockHolderAnimation = AnimationUtils.loadAnimation(ArticleActivity.this, R.anim.tab_up); 
    tabBlockHolderAnimation.setAnimationListener(new AnimationListener(){ 



    @Override 
    public void onAnimationEnd(Animation animation) { 

    // TODO Auto-generated method stub 

    homeTabBar.setVisibility(View.GONE); 
    } 
}); 

tabBlockHolderAnimation.setFillAfter(true); 

homeTabBar.startAnimation(tabBlockHolderAnimation); 

回答

13
public void toggle() { 
    TranslateAnimation anim = null; 

    isOpen = !isOpen; 

    if (isOpen) { 
     layoutRoot.setVisibility(View.VISIBLE); 
     anim = new TranslateAnimation(0.0f, 0.0f, layoutRoot.getHeight(), 0.0f); 
    } else { 
     anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, layoutRoot.getHeight()); 
     anim.setAnimationListener(collapseListener); 
    } 

    anim.setDuration(300); 
    anim.setInterpolator(new AccelerateInterpolator(1.0f)); 
    layoutRoot.startAnimation(anim); 
} 

Animation.AnimationListener collapseListener = new Animation.AnimationListener() { 
    public void onAnimationEnd(Animation animation) { 
     layoutRoot.setVisibility(View.GONE); 
    } 

    @Override 
    public void onAnimationRepeat(Animation animation) { 
    } 

    @Override 
    public void onAnimationStart(Animation animation) { 
    } 
}; 
+3

我得到了相同的結果,我的實現。 – Switch

+1

嘿,非常漂亮的代碼。我用它。我只有一個問題。 layoutRoot在我摺疊和動畫偵聽器調用View.GONE時閃爍。 當我不使用View.GONE而是anim.fillAfter(true)時,它不會閃爍,但組件的位置不會隨動畫更改。你沒有這個問題嗎? – vandzi

+0

佈局閃爍是因爲它將視圖添加到佈局,所以您可以使用View.INVISIBLE,但缺點是它會佔用現有佈局中的空間,因此它可能會看起來很糟糕並帶有空白區域。 – PravinDodia