Why do child views inherit the alpha value from parent layout

slayton picture slayton · Sep 13, 2011 · Viewed 9.3k times · Source

In my app I've set a background image of the top level linearlayout and then to fade the background I set its alpha to .2 but this creates an odd problem in that it also sets the alpha for all children of the layout as well, even if I explicitly define a different alpha value in the children.

Is it possible to set the alpha value of a parent and not affect that of the child?

What is there a proper way to set the alpha on top level view without affecting the alpha on that views children?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll1" 
    android:orientation="vertical"
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"
    android:gravity="center"
    android:background="@drawable/bg"
    android:alpha="0.2">
        <Button android:id="@+id/btn1" 
            android:text="Set 1"
            android:layout_width="300px"
            android:layout_height="150px" 
            android:layout_gravity="center" 
            android:background="@drawable/button1"
            android:tag="1"
            android:alpha="1"/>
        <Button android:id="@+id/btn2" 
            android:text="Set 2"
            android:layout_width="300px" 
            android:layout_height="150px" 
            android:layout_gravity="center" 
            android:background="@drawable/button2"
            android:tag="2"/>
</LinearLayout>

Answer

Dave picture Dave · Sep 13, 2011

That is exactly how it is intended to work.

Why not simply change the alpha of your background drawable "@drawable/bg" to 0.2?

Alternatively, try a FrameLayout with this basic structure:

<FrameLayout>
    <ImageView
        android:background="@drawable/bg" 
        android:alpha="0.2" />
    <LinearLayout>
        <Button />
        <Button />
    </LinearLayout>     
</FrameLayout>