Skip to main content

Translucent Theme

[ Reference ]

Description

Style and base class for creating activities with a translucent background.


Usage

tip

This is the recommended structure for the activity layout file.

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityName">

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<!--
LinearLayout or any other layout.
You can use fixed or relative width and height.
-->
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#000000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<!-- ... -->

</androidx.appcompat.widget.LinearLayoutCompat>

</androidx.constraintlayout.widget.ConstraintLayout>

</RelativeLayout>

1.- In the AndroidManifest assign the theme AndroidUtilsTheme.Translucent to the desired activity.

<activity
android:name=".about.AboutActivity"
android:theme="@style/AndroidUtilsTheme.Translucent" />

2.- In the desired activity, inherit from TranslucentActivity which in turn inherits from AppCompatActivity.

class AboutActivity : TranslucentActivity() { ... }

3.- Assign the value to the activityOpacity property in the place where you want to adjust the opacity of the activity, so that the activity has the background when it starts, you must assign the value before super.onCreate(savedInstanceState) in the onCreate(). The property can be reassigned anywhere and the change is instantly reflected. The value must be between 0 and 1, which corresponds to an opacity of 0% and 100% respectively.

override fun onCreate(savedInstanceState: Bundle?) {
super.activityOpacity = 0.9f
super.onCreate(savedInstanceState)
}

Usage example (design)
Usage example (code)


Considerations

To produce the best opacity effect in the activity, the dimAmount property of the window is used to control the opacity. In some cases (such as when a dialog is displayed) it has its own dimAmount value, and when that value is less than the activityOpacity, an unwanted effect is generated in the view. To correct this, the TranslucentActivity activity has a special function called configureWindowDim that must be invoked when a view is to be displayed above of the activity, this corrects this problem and maintains the appropriate opacity. For example, to adjust in a dialog:

val dialog = MaterialAlertDialogBuilder(this@AboutActivity).setTitle("DEMO").show()
configureWindowDim(dialog.window)

In the following image you can see an activity with an opacity of 90%, and the effect generated by calling configureWindowDim or not.