Error popup android

Android popup error for TextView without focus. GitHub Gist: instantly share code, notes, and snippets.
/** * As TextView (and EditText as a subclass) * can show error if it is in focus only * (many thanks to person who added this if condition to Android source code) — * we have to create own popup window and style it with custom styles * (internal styles are unavailable for developers). * This is helper to show / hide popup errors and drawable icons for TextView. */ public class ErrorPopupHelper { private ErrorPopup mErrorPopup; private TextView lastTextView; /** * Hide error if user starts to write in this view */ private TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (mErrorPopup != null && mErrorPopup.isShowing()) { cancel(); } } @Override public void afterTextChanged(Editable editable) { } }; public void setError(TextView mTextView, int stringResId) { setError(mTextView, mTextView.getContext().getString(stringResId)); } public void setError(TextView mTextView, CharSequence error) { cancel(); CharSequence mError = TextUtils.stringOrSpannedString(error); if (mError != null) { showError(mTextView, error.toString()); } mTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, mError == null ? 0 : android.R.drawable.stat_notify_error, 0); mTextView.addTextChangedListener(textWatcher); lastTextView = mTextView; } public void cancel() { if (lastTextView != null && lastTextView.getWindowToken() != null) { hideError(); lastTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); lastTextView.removeTextChangedListener(textWatcher); lastTextView = null; } } private void showError(TextView mTextView, String error) { if (mTextView.getWindowToken() == null) { return; } if (mErrorPopup == null) { LayoutInflater inflater = LayoutInflater.from(mTextView.getContext()); final TextView err = (TextView) inflater.inflate(R.layout.view_error_hint, null); final float scale = mTextView.getResources().getDisplayMetrics().density; mErrorPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f)); mErrorPopup.setFocusable(false); // The user is entering text, so the input method is needed. We // don’t want the popup to be displayed on top of it. mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } TextView tv = (TextView) mErrorPopup.getContentView(); chooseSize(mErrorPopup, error, tv); tv.setText(error); mErrorPopup.showAsDropDown(mTextView, getErrorX(mTextView), 0); mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor()); } private void hideError() { if (mErrorPopup != null) { if (mErrorPopup.isShowing()) { mErrorPopup.dismiss(); } mErrorPopup = null; } } private int getErrorX(TextView mTextView) { return mTextView.getWidth() — mErrorPopup.getWidth() — mTextView.getPaddingRight(); } private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { int wid = tv.getPaddingLeft() + tv.getPaddingRight(); int ht = tv.getPaddingTop() + tv.getPaddingBottom(); int defaultWidthInPixels = tv.getResources().getDimensionPixelSize( R.dimen.textview_error_popup_default_width); Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, Layout.Alignment.ALIGN_NORMAL, 1, 0, true); float max = 0; for (int i = 0; i < l.getLineCount(); i++) { max = Math.max(max, l.getLineWidth(i)); } /* * Now set the popup size to be big enough for the text plus the border capped * to DEFAULT_MAX_POPUP_WIDTH */ pop.setWidth(wid + (int) Math.ceil(max)); pop.setHeight(ht + l.getHeight()); } }

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.

popup1

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

android popup box 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

dependencies { // ... implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' // ... }

Code language: Kotlin (kotlin)

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:

<?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>

Code language: HTML, XML (xml)

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

class PopUpWindow : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition(0, 0) setContentView(R.layout.popup_window) // ... } }

Code language: Kotlin (kotlin)

Use Bundle to get the data we’ll pass later on when we call the popup window from the MainActivity

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 } }

Code language: Kotlin (kotlin)

Set the data to the TextViews and Button

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 // ... } }

Code language: Kotlin (kotlin)

Make the status bar appearance transparent at different API levels

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 } }

Code language: Kotlin (kotlin)

Create a fade animation for the popup window background when the Activity starts

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() // ... } }

Code language: Kotlin (kotlin)

Create the fade animation for the popup window too

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() // ... } }

Code language: Kotlin (kotlin)

Close the popup window with fade animation when you press the ‘OK’ button or the back button on your device.

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() } }

Code language: Kotlin (kotlin)

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!’

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) } } }

Code language: Kotlin (kotlin)
You can find the final project here

If you have any questionsplease feel free to leave a comment below

Improve Article

Save Article

  • Read
  • Discuss
  • 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:

    1. 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'

    }

    1. 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();
        }
    }
    

    Понравилась статья? Поделить с друзьями:
  • Error populating transaction anaconda is retrying при установке centos
  • Error populating transaction after 10 anaconda retries
  • Error poll or select is needed to compile rabbitmq c
  • Error pointer of type void used in arithmetic
  • Error po7 canon mp250