Button states with Background as AnimationDrawable in Android

前端 未结 2 1277
梦谈多话
梦谈多话 2020-12-03 03:47

I have made custom buttons in Android for a while. Things were simple, just made image resources for button states and made a selector for it. Everything went smooth and nic

相关标签:
2条回答
  • 2020-12-03 04:35

    My answer is a bit late, I know, but I faced the same issue. I checked a lot of solutions, but found only one. I have tried to start the animation in onWindowFocusChanged(), start the animation in aseparate thread, but it doesn't help.

    I solved this issue using setVisible (boolean visible, boolean restart)

    So you can try this:

        private Button ImgBtn;
        private AnimationDrawable btnAnimation;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btn = (Button)findViewById(R.id.button1);
            StateListDrawable background = (StateListDrawable) btn.getBackground();
            btnAnimation = (AnimationDrawable) background.getCurrent();
            btnAnimation.setVisible(true, true); // it works even in onCreate()        
        }
    

    Hope this will help somebody :)

    0 讨论(0)
  • 2020-12-03 04:37

    You're doing incorrect cast -- your background drawable is StateListDrawable, not AnimationDrawable. I'd rather do something like:

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
      super.onWindowFocusChanged(hasFocus);
      btn = (Button)findViewById(R.id.btnAnim);
      StateListDrawable background = (StateListDrawable) btn.getBackground();
      Drawable current = background.getCurrent();
      if (current instanceof AnimationDrawable) {
          btnAnimation = (AnimationDrawable) current;
          btnAnimation.start();
      }
    }
    
    0 讨论(0)
提交回复
热议问题