Alpha animation not working

2019-07-04 03:28发布

问题:

Pretty simple: I add a dynamic button on screen and I try to fade it out after adding, but the animation never plays. I tried adding it later when it is already rendered on the screen, but still nothing. Below is the code:

btn = new ImageButton(context);
btn.setBackgroundColor(0xFFFF0000);

params = new WindowManager.LayoutParams(
    width,height,
    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT | 
    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;

windowManager.addView(btn, params);

btn.startAnimation(new AlphaAnimation(1,0));

Any ideas?

回答1:

Try this:

btn.setAlpha(0f);
btn.animate().alpha(1).setDuration(1000);


回答2:

This answer may explain why you're getting such strange behavior if you've set the alpha to 0 in xml.