32

I've found this question and I have almost the same problem. How could I apply alpha only to a relative layout and not to it's children? Could anyone help?

I have a rectangular LinearLayout that has some margin, some round corners and an alpha value of 0.3. Inside this layout I have 4 different layouts as I display different images in different positions. My issue is that although the primary layout is 0.3, I want my child to be fully visible, or not affected by it's parent alpha, and I am wondering how I can please do that please? I have tried setting alpha=1 on the children layouts but it did not work. Setting it to 0 does make the children layout disappear though, so it seems I can reduce below 0.3 but not anything above the parent. Is that a bug or am I doing it wrong please? Thank you.

Alin
  • 1,044
  • 6
  • 20
  • 42

1 Answers1

38

Instead of setting the alpha of the parent you can use FrameLayout and set a background image first and set the alpha of that child. For example

Instead of using this

<LinearLayout 
        android:background="@drawable/background" 
        android:alpha="0.3" >
    <LinearLayout>
        <Button />
        <Button />
    </LinearLayout>     
</LinearLayout >

Use this one

<FrameLayout>
    <ImageView
        android:background="@drawable/background" 
        android:alpha="0.3" />
    <LinearLayout>
        <Button />
        <Button />
    </LinearLayout>     
</FrameLayout>
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • 4
    This answer seems the best solution at the Xml level. Answers at *"Already answered this question link above"* don't mention this approach . Thanks! – Gene Bo Mar 02 '17 at 01:04
  • Gives: `java.lang.RuntimeException: Binary XML file line #4: You must supply a layout_width attribute.` But `ImageView` with `android:layout_width="match_parent"` and `android:layout_height="match_parent"` doesn't improve it. – gotwo Apr 22 '20 at 19:14