Making transparent background for Activity when using AppCompat and Support Design Library
Today’s post will be quite short and related to the problem I encountered at work lately. We are using activities with semi-transparent backgrounds (for dimmed tutorials). I’m not saying it’s the best solution, but it works from android 2.3 up to 5.1 quite nicely. To approach this, you can simply new activity’s theme in AndroidManifest
like this:
1 2 3 4 | <activity android:name=".activity.SampleActivity" android:label="@string/app_name" android:theme="@style/Theme.Translucent.NoTitleBar" /> |
and set activity’s background color to #C0000000
(it will give you semi-transparent black background).
i.e.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#C0000000"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="android is awesome!" android:textColor="#FFFFFF" /> </RelativeLayout> |
Everything was working fine, unless you put elements from Android Design Support Library
(for example fab button) into your layout.
If you do so, “nice” exception will be thrown:
java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x12
What it means is your Activity doesn’t inherit from AppCompatActivity
class and cannot find resources.
To fix this problem you need to do two things:
Inherit from AppCompatActivity
class
Create transparent theme for AppCompat
since it doesn’t have one.
As for first point it’s quite easy, second one took me a while to do it right so… here’s the solution:
1 2 3 4 5 6 7 | <style name="TransparentCompat" parent="@style/Theme.AppCompat.Light.DarkActionBar"> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:colorBackgroundCacheHint">@null</item> <item name="android:windowIsTranslucent">true</item> <item name="android:windowAnimationStyle">@android:style/Animation</item> </style> |