Android popup box :
Introduction :
Android popup box, Generally we see android popup box appearing in the apps showing alert messages or system errors. And also sometimes we can enter data into these windows which can be further processed depending upon our app requirement.
We use these types of popup boxes so that we can customize the data which is not possible in general dialog’s.
You can see the below window which is the android popup box we are going to learn in this tutorial.
The popup box intakes a text i.e., your name and will display a toast when ok button is clicked and popup box is closed when cancel button is clicked.
And also you can notice we have placed a logo and heading you can change the design according to your requirement.
We can also display listview in the popup box that we will see in our further tutorials, not only listview we can show maps, images, and many more….
activity_main.xml :
Add a textview and a button to the activity.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:paddingLeft="20dp" android:paddingRight="20dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Popup Box" android:gravity="center" android:id="@+id/textView" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click to open a popup box" android:layout_marginTop="40dp" android:id="@+id/button" android:layout_gravity="center_vertical" /> </LinearLayout>
MainActivity.java :
We will be calling the pop up box on button click in main activity. Also you can use View binding here for better efficiency.
package com.example.abhishek.popup; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends ActionBarActivity { Button popupbut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); popupbut = (Button)findViewById(R.id.button); popupbut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this,Popup.class); startActivity(i); } }); } }
Creating popup.xml :
Now we will be creating popup activity by adding imageview for logo and textviews, button and edittext for accepting text to be displayed as toast.
This dialog is a bit flexible because here you can customize the components just like you do in normal activity.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="300dp" android:layout_height="200dp" android:orientation="vertical" android:background="#ffffff" android:gravity="center"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:id="@+id/imageView" android:layout_width="70dp" android:layout_height="70dp" android:background="@drawable/logo"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="10dp"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Welcome to AndroidCoding.in" android:gravity="center" android:layout_marginTop="10dp" android:textSize="15dp" android:textStyle="bold" android:textColor="#000000"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:hint="enter your name" android:textColor="#000000" android:textColorHint="#000000" android:layout_marginTop="30dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="20dp" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ok" android:id="@+id/but1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:layout_marginLeft="10dp" android:id="@+id/but2" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout>
Creating popup.java :
Initialize buttons, edittext and setOnClickListener for two buttons.
but1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = editText.getText().toString(); Toast.makeText(Popup.this, "Your name is "+msg, Toast.LENGTH_SHORT).show(); } }); but2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Popup.this.finish(); } });
package com.example.abhishek.popup; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * Created by Abhishek on 9/25/2016. */ public class Popup extends Activity{ EditText editText; Button but1,but2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.popup); editText = (EditText)findViewById(R.id.editText); but1 = (Button)findViewById(R.id.but1); but2 = (Button)findViewById(R.id.but2); but1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = editText.getText().toString(); Toast.makeText(Popup.this, "Your name is "+msg, Toast.LENGTH_SHORT).show(); } }); but2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Popup.this.finish(); } }); } }
AndroidManifest.xml :
Add android popup box activity as we are converting the activity to dialog.
<activity android:name=".Popup" android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"/>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.abhishek.popup" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Popup" android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"/> </application> </manifest>
Android popup box output :
This screen depicts the usage of android popup box
In this tutorial on android popup box if you have any queries do let us know in the comment section below.
For more interesting tutorials like and share this tutorial.
Last updated on: January 3, 2020
Today, I’m going to show you how to create very easy a nice popup window with a semi-transparent background!
In this example I’m using CardView to have rounded corners in the popup window. If you don’t like it, and you want to use something else (RelativeLayout, FrameLayout e.t.c), just skip the next step.
Adding the CardView library
If you like your popup window to have rounded corners, add the cardView library to your build.gradle of your app module
Code language: Kotlin (kotlin)
dependencies { // ... implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' // ... }
Creating the Popup Window Activity
Create a new Empty Activity in your project. In this example, we call it PopUpWindow
Go to the xml layout and paste the following code:
Code language: HTML, XML (xml)
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/popup_window_background" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".PopUpWindow"> <androidx.cardview.widget.CardView android:id="@+id/popup_window_view_with_border" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" app:cardBackgroundColor="#FFFFFF" app:cardCornerRadius="3dp" app:cardElevation="0dp" app:cardMaxElevation="0dp" app:cardPreventCornerOverlap="false" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.cardview.widget.CardView android:id="@+id/popup_window_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="2dp" app:cardBackgroundColor="@android:color/white" app:cardCornerRadius="3dp" app:cardElevation="0dp" app:cardMaxElevation="0dp" app:cardPreventCornerOverlap="false"> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/popup_window_background_container" android:layout_width="250dp" android:minHeight="170dp" android:background="#bc214b" android:layout_height="wrap_content" android:layout_centerInParent="true"> <androidx.appcompat.widget.AppCompatTextView android:id="@+id/popup_window_text" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" android:text="Text" android:gravity="center" android:textAlignment="center" android:textStyle="bold" android:textColor="#FFFFFF" android:textSize="12sp" app:layout_constraintBottom_toTopOf="@+id/popup_window_button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/popup_window_title" /> <androidx.appcompat.widget.AppCompatTextView android:id="@+id/popup_window_title" android:layout_width="match_parent" android:layout_height="45dp" app:autoSizeTextType="uniform" app:autoSizeMaxTextSize="24dp" android:background="#9E1C40" android:text="Title" android:gravity="center" android:textAlignment="center" android:textColor="#FFFFFF" android:textSize="20sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/popup_window_button" style="?android:attr/borderlessButtonStyle" android:layout_width="match_parent" android:layout_height="40dp" android:background="#851635" android:text="ok" android:textAllCaps="false" android:textColor="#FFFFFF" android:textSize="20sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout>
Go to your activity file (PopUpWindow.kt) and disable Activity’s open/close animation by giving the number 0 on the overridePendingTransition before the setContentView
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition(0, 0) setContentView(R.layout.popup_window) // ... } }
Use Bundle to get the data we’ll pass later on when we call the popup window from the MainActivity
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { private var popupTitle = "" private var popupText = "" private var popupButton = "" private var darkStatusBar = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // Get the data val bundle = intent.extras popupTitle = bundle?.getString("popuptitle", "Title") ?: "" popupText = bundle?.getString("popuptext", "Text") ?: "" popupButton = bundle?.getString("popupbtn", "Button") ?: "" darkStatusBar = bundle?.getBoolean("darkstatusbar", false) ?: false } }
Set the data to the TextViews and Button
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // Set the data popup_window_title.text = popupTitle popup_window_text.text = popupText popup_window_button.text = popupButton // ... } }
Make the status bar appearance transparent at different API levels
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { private var popupTitle = "" private var popupText = "" private var popupButton = "" private var darkStatusBar = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // Set the Status bar appearance for different API levels if (Build.VERSION.SDK_INT in 19..20) { setWindowFlag(this, true) } if (Build.VERSION.SDK_INT >= 19) { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } if (Build.VERSION.SDK_INT >= 21) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // If you want dark status bar, set darkStatusBar to true if (darkStatusBar) { this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } this.window.statusBarColor = Color.TRANSPARENT setWindowFlag(this, false) } } // ... } private fun setWindowFlag(activity: Activity, on: Boolean) { val win = activity.window val winParams = win.attributes if (on) { winParams.flags = winParams.flags or WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS } else { winParams.flags = winParams.flags and WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS.inv() } win.attributes = winParams } }
Create a fade animation for the popup window background when the Activity starts
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // Fade animation for the background of Popup Window val alpha = 100 //between 0-255 val alphaColor = ColorUtils.setAlphaComponent(Color.parseColor("#000000"), alpha) val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), Color.TRANSPARENT, alphaColor) colorAnimation.duration = 500 // milliseconds colorAnimation.addUpdateListener { animator -> popup_window_background.setBackgroundColor(animator.animatedValue as Int) } colorAnimation.start() // ... } }
Create the fade animation for the popup window too
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // Fade animation for the Popup Window popup_window_view_with_border.alpha = 0f popup_window_view_with_border.animate().alpha(1f).setDuration(500).setInterpolator( DecelerateInterpolator() ).start() // ... } }
Close the popup window with fade animation when you press the ‘OK’ button or the back button on your device.
Code language: Kotlin (kotlin)
class PopUpWindow : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // Close the Popup Window when you press the button popup_window_button.setOnClickListener { onBackPressed() } } override fun onBackPressed() { // Fade animation for the background of Popup Window when you press the back button val alpha = 100 // between 0-255 val alphaColor = ColorUtils.setAlphaComponent(Color.parseColor("#000000"), alpha) val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), alphaColor, Color.TRANSPARENT) colorAnimation.duration = 500 // milliseconds colorAnimation.addUpdateListener { animator -> popup_window_background.setBackgroundColor( animator.animatedValue as Int ) } // Fade animation for the Popup Window when you press the back button popup_window_view_with_border.animate().alpha(0f).setDuration(500).setInterpolator( DecelerateInterpolator() ).start() // After animation finish, close the Activity colorAnimation.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { finish() overridePendingTransition(0, 0) } }) colorAnimation.start() } }
To use the popup window, just pass the values for the Title, Text, Button text and Status Bar appearance.
In this example, when you press the button in the MainActivity, it shows the popup window with title ‘Error’ and text ‘Sorry, that email address is already used!’
Code language: Kotlin (kotlin)
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) show_btn.setOnClickListener { val intent = Intent(this, PopUpWindow::class.java) intent.putExtra("popuptitle", "Error") intent.putExtra("popuptext", "Sorry, that email address is already used!") intent.putExtra("popupbtn", "OK") intent.putExtra("darkstatusbar", false) startActivity(intent) } } }
You can find the final project here
If you have any questions, please feel free to leave a comment below
Improve Article
Save Article
Improve Article
Save Article
In this article, we learn about how to create a popup message with the help of Alerter Library. It is better to use Alerter than using Toast or Snackbar in cases if some alert messages are to be displayed to the user. We can add various onClickListeners to our alerter message which makes it better and it also has nice appealing UI. Approach:
- Add the support Library in build.gradle file and add dependency in the dependencies section. This library facilitates easy integration of Alert View in the app. The alert view is customizable and it is displayed over the ongoing activity in the app. This library is also compatible with AndroidX.
XML
dependencies {
implementation 'com.tapadoo.android:alerter:2.0.4'
}
- Now add the following code in the activity_main.xml file. This codes add a button in the MainActivity and if the button is clicked then showAlerter function is invoked.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showAlerter"
android:text="Show Alerter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.geeksforgeeks.gfgAlerter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.tapadoo.alerter.Alerter;
import com.tapadoo.alerter.OnHideAlertListener;
import com.tapadoo.alerter.OnShowAlertListener;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
}
public void showAlerter(View v)
{
Alerter.create(this)
.setTitle("Alert Title")
.setText("Alert Text")
.setIcon(
R.drawable.ic_android_black_24dp)
.setBackgroundColorRes(
R.color.colorAccent)
.setDuration(3000)
.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v)
{
// do something when
// Alerter message was clicked
}
})
.setOnShowListener(
new OnShowAlertListener() {
@Override
public void onShow()
{
// do something when
// Alerter message shows
}
})
.setOnHideListener(
new OnHideAlertListener() {
@Override
public void onHide()
{
// do something when
// Alerter message hides
}
})
.show();
}
}