Creating a Floating Alert Dialog like google translate with Material Design 3 in android
Before we jump into the main topic, let us take a moment to understand what is material design 3?
Material Design 3
As per the official documentation, Material Design 3 has an expanded color system that takes advantage of features such as dynamic color. If you use Material Theme Builder to reconfigure your palettes, you can simply drop in the Android XML or Compose theme code. For more details, you can see from here.
Today I’m going to show you how to create a Floating alert dialog like tap to translate features in the google translate app using a material design 3. The google translate app can open a floating alert dialog wherever you want to select a text. My approach is simple. At first, I will create a translucent theme that actually inheritance from Theme.Material3.DayNight.NoActionBar
after that, I will set the theme for the activity which will open when a floating dialog appears on the screen.
Let’s get started, Firstly we will add material design dependency in the appbuild.gradle
file. Find out from here.
dependencies {
// Material design 3 dependency
implementation 'com.google.android.material:material:1.6.0'
// ...
}
Note: In order to use the new Material3 themes and component styles, you should depend on version 1.5.0 or later.
That’s it for adding the dependency to our app. Now we are able to write code material design 3 related stuff.
Now, I’m going to customize my theme that actually will attach to my activity which will open when the floating dialog appears on the screen. Add the following code in the res/values/styles.xml file.
<!-- This is the theme which is being used in our floating window-->
<style name="Theme.FloatingWindow" parent="Theme.Material3.DayNight.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
<!--window animation style-->
<item name="android:windowAnimationStyle">@android:style/Animation</item>
<!--alert dialog theme-->
<item name="materialAlertDialogTheme">@style/ThemeOverlay.App.MaterialAlertDialog</item>
</style>
Now, Our translucent theme is ready but We have to add some styles for the alert dialog. Here is the below code snippet,
<style name="ThemeOverlay.App.MaterialAlertDialog" parent="ThemeOverlay.Material3.MaterialAlertDialog">
<item name="alertDialogStyle">@style/MaterialAlertDialog.App</item>
</style>
<!-- Theme for alert dialog -->
<style name="MaterialAlertDialog.App" parent="MaterialAlertDialog.Material3">
<item name="shapeAppearance">@style/ShapeAppearance.App.MediumComponent</item>
<item name="shapeAppearanceOverlay">@null</item>
</style>
We can change the alert dialog shape using the material ShapeAppearance. There are two types of corner Family rounded and cut
Rounded shape appearance
<style name="ShapeAppearance.App.MediumComponent" parent="ShapeAppearance.Material3.MediumComponent">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">12dp</item>
</style>
Here is the Cut shape appearance style
<style name="ShapeAppearance.App.MediumComponent" parent="ShapeAppearance.Material3.MediumComponent">
<item name="cornerFamily">cut</item>
<item name="cornerSize">12dp</item>
</style>
Our theme design is completed. Before moving to the main coding part we need to set the theme in AndroidManifest.xml. If you want to apply the theme only to the specific activity at that time you have to set the theme inside the activity tag in AndroidManifest.xml. Otherwise, You have to add it inside the application tag.
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FloatingWindowLikeGoogleTranslate"
tools:targetApi="31">
How to detect the android system to our apps when selecting any text on the phone. That’s a big question, Right? At that moment, the Intent filter comes with the proper solution. The intent filter will register your app to the android system for the specific action. We will register our app for the text selection action.android.intent.action.PROCESS_TEXT
action will be registered our app to the android system for text selection. Add this code snippet inside the activity tag in the AndroidManifest.xml
<intent-filter>
<!--Register Intent filter for text selection any where -->
<action android:name="android.intent.action.PROCESS_TEXT"/>
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
Note: android.intent.action.PROCESS_TEXT
support API level 23 and above.
Now let’s move to the mainActivity.kt
Inside mainActivit
we will write two methods hasIntent()
andshowAlertDialog().
We will extract text that’s selected from anywhere using hasIntent()
method and we will be shown on the alert dialog.
private fun hasIntent() {
if (intent != null) {
var text: String? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Intent.EXTRA_PROCESS_TEXT support from 23 or above
text = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString()
}
showAlertDialog(text ?: "Floating window like alert dialog...")
} else {
showAlertDialog("Floating window like alert dialog...")
}
}
Material alert dialog
Here is the material alert dialog code. If you want to add a custom layout design, you can set using setView()
the method. Here I set setOnDismissListener
and inside setOnDismissListener
we called onBackPressed()
cause when the floating dialog is dismissed we also onBackPressed
to the activity.
private fun showAlertDialog(selectedText: String) {
MaterialAlertDialogBuilder(this)
.setIcon(R.drawable.ic_launcher_foreground)
//.setView() you can set custom view here
.setTitle("Floating Window")
.setMessage(selectedText)
.setOnDismissListener {
onBackPressed()
}
.setPositiveButton("Ok") { dialog, _ ->
dialog.dismiss()
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
onBackPressed()
}
.create().apply {
window?.setGravity(Gravity.TOP)
show()
}
}
Here is the full implementation of mainActivity.kt
package com.poran.floatingwindowlikegoogletranslate
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Removed setContentView() method because we don't need any
// mainActivity related ui that's why i removed.
//extract intent data
hasIntent()
}
private fun showAlertDialog(selectedText: String) {
MaterialAlertDialogBuilder(this)
.setIcon(R.drawable.ic_launcher_foreground)
//.setView() you can set custom view here
.setTitle("Floating Window")
.setMessage(selectedText)
.setOnDismissListener {
onBackPressed()
}
.setPositiveButton("Ok") { dialog, _ ->
dialog.dismiss()
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
onBackPressed()
}
.create().apply {
window?.setGravity(Gravity.TOP)
show()
}
}
private fun hasIntent() {
if (intent != null) {
var text: String? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Intent.EXTRA_PROCESS_TEXT support from 23 or above
text = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString()
}
showAlertDialog(text ?: "Floating window like alert dialog...")
} else {
showAlertDialog("Floating window like alert dialog...")
}
}
}
Congratulations! We are completed writing the code.
Here is the look of our floating material dialog.
Here is the final result that we expected.
You can find the full source code in my Github repository
If you found this post helpful, feel free to clap! 👏 Thanks for reading.
You can connect with me on Linkedin!
If you like my content and want to support my work, you can give me a cup of coffee ☕️ 🥰