0

In my app, I have a service in which I create a view that I display by using WindowManger :

    mFilter = new View(this);
    mFilter.setBackgroundColor(getResources().getColor(android.R.color.black));

    mParams = new WindowManager.LayoutParams(
        LayoutParams.TYPE_SYSTEM_OVERLAY,
        LayoutParams.FLAG_LAYOUT_IN_SCREEN,
        PixelFormat.TRANSPARENT); // PixelFormat.TRANSLUCENT works as well

    mWindowManager.addView(mFilter, mParams);

I want to be able to control its opacity dynamically this way :

    mParams.alpha = alpha; // alpha is a float chosen by the user and varying from 0 to 1
    mWindowManager.updateView(mFilter, mParams);

The problem is that it works perfectly well on my galaxy s3 under android 4.2.2, on my galaxy ace under android 2.3.6, on an emulator under android 2.3.3 BUT it fails on my galaxy y under android 2.3.3 : the alpha cannot be set to a value between 1 and 0, so it is either fully transparent (0) or fully opaque (1). My questions are : does anyone have the same issue ? Does it occur only with this phone ? Is there a way to solve it or any other wayto change the opacity ? I've already search the web for a long time but no one seems to have experienced the same thing... I found a workaround that "half" works by setting directly the opacity of the view :

    mFilter.getBackground().setAlpha(alpha); // alpha is an int varying from 0 to 255

The problem this time is that on older version of android it works but on api 10 and lower, the view's opacity doesn't update even if I call, mFilter.postInvalidate() or mWindowManager.updateView(mFilter, mParams). I have to remove it (mWindowManager.removeView(mFilter)) and then add it again but it causes the screen to blink so it is not acceptable...

1 Answers1

1

It's some kind of a hack, but due to the alpha changes in various Android Versions I often use AlphaAnimation to set the opacity of a View, cause this is a reliable way even on older plattforms.

Just give it a try:

float alpha = 0.5f;
AlphaAnimation alphaAnimation = new AlphaAnimation(alpha, alpha);
alphaAnimation.setStartTime(0);
alphaAnimation.setDuration(0);
alphaAnimation.setFillAfter(true);
view.setAnimation(alphaAnimation);
view.postInvalidate();`
fish
  • 828
  • 1
  • 6
  • 14
  • Your answer worked after some correction but I finally achieved what I was looking for after adding my view to a `FrameLayout` and then set its opacity with `view.getBackground().setAlpha(alpha)` and then invalidate the view. It doesn't fully answer my problem because I would like to use WindowManger.LayoutParams.alpha... Thank you anyway. – Sébastien Morand May 10 '13 at 16:48
  • This doesn't work when a user disables device animations. – Denny Apr 13 '17 at 19:08