2015-11-08 72 views
0

我想用淡入/淡出動畫每隔10秒更改一次相對佈局的背景。 所以我發現如何更改android背景每個???秒?

//Transitiondrawable 
TransitionDrawable transition = (TransitionDrawable) viewObj.getBackground(); 
transition.startTransition(transitionTime); 

但它僅支持2繪製對象,我想添加更多 有沒有辦法做到這一點?

回答

1

首先實現MyAnim.java類,如下:

public class MyAnim extends Animation { 


    private final RelativeLayout view; 
    private int targetBackGround; 


    public MyAnim(RelativeLayout view, int tagetBackGroundColor) { 
     this.view = view; 
     this.targetBackGround = tagetBackGroundColor; 
    } 
    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) { 
     super.applyTransformation(interpolatedTime, t); 
     view.setBackgroundColor(targetBackGround); 
    } 


    public void setColor(int color) { 
     this.targetBackGround = color; 
    } 
} 

然後將下面的代碼添加到您的活動中,並在需要的地方調用animateBackground()方法:

private MyAnim backgroundAnim; 
    private int i; 

    private void animateBackground(){ 
     final RelativeLayout animLay = (RelativeLayout) findViewById(R.id.animLay); 
     final int colors[] = new int[]{Color.RED, Color.CYAN, Color.DKGRAY, Color.GREEN, Color.MAGENTA}; 
     backgroundAnim = new MyAnim(animLay, colors[i]); 
     backgroundAnim.setDuration(1000); 
     animLay.startAnimation(backgroundAnim); 

     backgroundAnim.setAnimationListener(new Animation.AnimationListener() { 
      @Override 
      public void onAnimationStart(Animation animation) { 

      } 

      @Override 
      public void onAnimationEnd(Animation animation) { 

       if (i == colors.length - 1) { 
        i = 0; 
       } else { 
        i++; 
       } 
       backgroundAnim.setColor(colors[i]); 
       animLay.startAnimation(backgroundAnim); 


      } 

      @Override 
      public void onAnimationRepeat(Animation animation) { 

      } 
     }); 
    } 
+0

謝謝,這絕對是我想要的 現在我怎麼能在動畫中使用淡入淡出來改變背景顏色 –

2

您可以創建自己的循環,類似:

int delayBetweenAnimations = 10000; 

    for (int i = 0; i < yourImagesArray.length ; i++) { 

     int delay = i * delayBetweenAnimations; 

     yourImageview.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       //set your image and animation here 
      } 
     }, delay); 

    } 

另一種方法是使用遞歸的動畫:

  @Override  
      public void onAnimationEnd(Animator animation) { 
       if(check_if_you_Still_want to_loop){ 
        //rerun your animation 
       } 
      } 
+0

在設置背景如何設置背景數組? –

+0

int [] imageList = new int [] {R.drawable.image1,R.drawable.image2 ...}; –

+0

我知道這個,但我問如何設置背景陣列 非常感謝我的朋友 –