Search code examples
androidandroid-layoutopacityandroid-relativelayout

Change the opacity/transparency of a view and affect the child views too


I have a relative layout with child TextViews.
The background of the parent RelativeLayout is white and I was wondering how I could change the alpha to change the opacity of the whole view programmatically (including children).
I am trying:

getBackground().setAlpha(0.4);  

But that expects an int and not a float. If I do:

getBackground().setAlpha((int)(0.4 * 255));  

The latter changes the view but makes it darker than I want. Also the children do not seem to change. It seems to affect only the background while I want something that makes everything more "grayed" out/less transparent.
What am I doing wrong?


Solution

  • That's because you are changing the backgound of the layout and not the layout itself. So instead of myRelativeLayout.getBackground().setAlpha(), use this: myRelativeLayout.setAlpha(0.4f).