同时有多个AnimationDrawable

时间:2011-05-19 16:33:17

标签: android animation drawable

我想在应用启动的同时启动不同的动画。我在onWindowFocusChanged函数中为一个动画按钮添加了我的代码,我没有遇到任何问题。但是,当我尝试为另一个按钮设置动画时,第二个按钮不会移动,固定在第一个框架上。 任何人都知道我怎么能克服?

一些代码:

在OnCreate中:

public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);      
      setContentView(R.layout.main);
      Button mButtonPlay = (Button) findViewById(R.id.ButtonPlay);
      mButtonPlay.setBackgroundResource(R.drawable.button_play);      
      buttonAnimationPlay = (AnimationDrawable)mButtonPlay.getBackground();
      Button mButtonOptions = (Button) findViewById(R.id.ButtonOptions);
      mButtonOptions.setBackgroundResource(R.drawable.button_options);
      buttonAnimationOptions = (AnimationDrawable)mButtonPlay.getBackground();
  }
enter code here

在onWindowFocusChanged:

@Override
  public void onWindowFocusChanged(boolean hasFocus) 
  {
      if (hasFocus)
      {
    buttonAnimationPlay.start();  
    buttonAnimationOptions.start();  
      }
      else
      {   
    buttonAnimationPlay.stop();  
    buttonAnimationOptions.stop();  
      }
  }

1 个答案:

答案 0 :(得分:1)

好吧,我终于明白了!代码中有一个错误,多么糟糕!这是一个很好的:

  final Button mButtonPlay = (Button) findViewById(R.id.ButtonPlay);
  mButtonPlay.setBackgroundResource(R.drawable.button_play);
  buttonAnimationPlay = (AnimationDrawable)mButtonPlay.getBackground();


  final Button mButtonOptions = (Button) findViewById(R.id.ButtonOptions);
  mButtonOptions.setBackgroundResource(R.drawable.button_play);
  buttonAnimationOptions = (AnimationDrawable)mButtonOptions.getBackground();

无论如何,我还尝试过以编程方式添加视图,现在它也可以使用。对于任何人都会使用其中一种,这是另一种:

RelativeLayout Relative = (RelativeLayout) findViewById(R.id.RelativeForButtons);
  RelativeLayout.LayoutParams relativeParamsPlay = 
      new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  RelativeLayout.LayoutParams relativeParamsOptions = 
      new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

  relativeParamsPlay.addRule(RelativeLayout.BELOW,R.id.Title);
  relativeParamsPlay.addRule(RelativeLayout.CENTER_IN_PARENT);
  final Button mButtonPlay = new Button(this);
  mButtonPlay.setBackgroundResource(R.drawable.button_play);
  buttonAnimationPlay = (AnimationDrawable)mButtonPlay.getBackground();
  mButtonPlay.setId(1);
  mButtonPlay.setText("PLAY");
  Relative.addView(mButtonPlay,relativeParamsPlay);   

  final Button mButtonOptions = new Button(this);
  mButtonOptions.setBackgroundResource(R.drawable.button_options);
  buttonAnimationOptions = (AnimationDrawable)mButtonOptions.getBackground();
  mButtonOptions.setId(2);
  mButtonOptions.setText("OPTIONS");
  relativeParamsOptions.addRule(RelativeLayout.BELOW, mButtonPlay.getId());
  relativeParamsOptions.addRule(RelativeLayout.CENTER_IN_PARENT);
  Relative.addView(mButtonOptions,relativeParamsOptions);   

所有这些都在OnCreate函数中。如果你想开始动画,请使用onWindowFocusChanged函数,如上所述。

希望它有所帮助! :)