home top ad

Many custom alert dialog box with imageview in android programmatically

Hello,Guys Today, in this tutorials, we will learn how to use the alert dialog in our app . Alert dialog is a method used to give error, warning or any instructions to the user or we can also use it to exit the app.

What is the Alert Dialog Box ?

Alert dialog is a pop_ up box that we use when we have to give a message to the user like error, warning or any instruction. In the alert dialog, we can do a title, message and two or three buttons on which we can perform any operation by giving ok no or exit or any name .Today we will use a lot of alert dialog in which we will also use animation.


Create New Project

First of all, you have to create a project in your Android Studio. For this, you will first go to file and then go to new project and click and create a new project. As soon as we create a project, we will see two files, first activity_main.xml and MainActivity.java

Today we will create different types of alert dialog boxes using four types of methods.

Method 1:

In the first method, we will create a normal alert dialog using the layout.First of all we will take a button in activtiy_main on which we will display normal dialog using onClick

activity_main.xml

<?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:orientation="vertical">

    <Button
        android:id="@+id/alert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="131dp"
        android:text="Create Alert Dialog" />

</RelativeLayout>

Custom1.java

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class Custom1 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alert_dialogs);
        Button btn=findViewById(R.id.alert);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog dialog=new Dialog(Custom1.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.setContentView(R.layout.alert_dialog);
                dialog.show();
            }
        });
    }
}
Here after we have created a custom 1 class, using the onclick on the button in it, we will pass the context in a parameter in the dialog class, then set the background color on the dialog, then layout the dialog in the last dialog then dialog.show () ; The method will not run, otherwise the layout will not show. The code of alert_dialog is given below

alert_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:paddingLeft="15dp"
    android:paddingRight="15dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="100dp"
            android:layout_height="100dp"

            android:background="#053AF8"
            android:src="@drawable/error" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#053AF8"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Alert Dialog "
                android:textSize="30sp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#FFFFFF"
                android:textStyle="bold"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Method 2:

In the Second method, we will create a alert dialog without using the layout.First of all we will take a button in activtiy_main on which we will display normal dialog using onClick

activity_main.xml

<?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="@android:color/transparent"
    android:orientation="vertical"
    android:paddingLeft="15dp"
    android:paddingRight="15dp">

    <Button
        android:id="@+id/alert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="86dp"
        android:text="Create Alert Dialog" />
</RelativeLayout>

MainActivity.java

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class AlertDialogs extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.normal_alert_dialog);
        Button button = findViewById(R.id.alert);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                androidx.appcompat.app.AlertDialog.Builder build = new androidx.appcompat.app.AlertDialog.Builder(AlertDialogs.this);
                build.setIcon(android.R.drawable.ic_dialog_alert);
                build.setTitle("Alert Dialog ");
                build.setCancelable(false);
                build.setMessage("Do you want exit from app").setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AlertDialogs.this.finish();
                    }
                });

                build.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                androidx.appcompat.app.AlertDialog AlertDialog = build.create(); //now, show
                AlertDialog.show();
            }
        });
    }
}

Create a dialog using the AlertDialog.Builder class AlertDialog.Builder takes as a context parameter then by its object we will create a title and then a message and then two buttons named yes and no on which to onclick you For setPositiveButton () will take a method in which it will take a string such as yes and new DialogInterface.OnClickListener () public method and then likewise set setNegativeButton for No button will take the method, then string then DialogInterface.OnClickListener () will take public method and in Last. It is necessary to write the object.show of the .AlertDialog by creating the dialog box by AlertDialog, otherwise the dialog box will not appear in this picture.

Method 3:

In this method we have animation and two Android open source library 'com.nineoldandroids: library: 2.4.0' and We will use "com.github.sd6352051.niftydialogeffects: niftydialogeffects: 1.0.0@aar" to help us create various types of dialogs. Paste the library below into the build.gradle and press the Sync Now button.

 implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.github.sd6352051.niftydialogeffects:niftydialogeffects:1.0.0@aar'
After doing this, we will now paste the below given code in activity_main, in which we are using four buttons, on which many types of dialog will be displayed.

activity_main.xml

<?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:orientation="vertical">


    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Create Alert Dialog" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/btn1"
        android:text="Create Alert Dialog" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/btn2"
        android:text="Create Alert Dialog" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/btn3"
        android:text="Create Alert Dialog" />



</RelativeLayout>
After pasting this code, we will now implement this button in the animation class.

Animation.java

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;

public class Animation extends AppCompatActivity {

    private NiftyDialogBuilder materialDesignAnimatedDialog;
    private Button btn1, btn2, btn3, btn4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_layout);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        materialDesignAnimatedDialog = NiftyDialogBuilder.getInstance(this);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animatedDialog1(v);
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animatedDialog2(v);
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animatedDialog3(v);
            }
        });

        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animatedDialog4(v);
            }
        });

    }

    //You can use other different // effects like Slideleft, SlideBottom, Fadein, Newspaper, RotateBottom, RotateLeft, Slit.
    public void animatedDialog1(View view) {
        materialDesignAnimatedDialog.withTitle("Animated Fall Dialog Title")
                .withMessage("Add your dialog message here. Animated dialog description place.")
                .withDialogColor("#1c90ec").withButton1Text("OK").withButton2Text("Cancel").withDuration(700)
                .withEffect(Effectstype.Fall).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).show();
    }

    public void animatedDialog2(View view) {
        materialDesignAnimatedDialog.withTitle("Animated Flip Dialog Title").
                withMessage("Add your dialog message here. Animated dialog description place.")
                .withDialogColor("#1c90ec").withButton1Text("OK").withButton2Text("Cancel")
                .withDuration(700).withEffect(Effectstype.Fliph).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).show();
    }

    public void animatedDialog3(View view) {
        materialDesignAnimatedDialog.withTitle("Animated Shake Dialog Title").withMessage("Add your dialog message here. Animated dialog description place.").withDialogColor("#1c90ec").withButton1Text("OK").withButton2Text("Cancel").withDuration(700).withEffect(Effectstype.Shake).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).show();
    }

    public void animatedDialog4(View view) {
        materialDesignAnimatedDialog.withTitle("Animated Slide Top Dialog Title")
                .withMessage("Add your dialog message here. Animated dialog description place.")
                .withDialogColor("#1c90ec").withButton1Text("OK").withButton2Text("Cancel")
                .withDuration(700).withEffect(Effectstype.Slidetop).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDesignAnimatedDialog.cancel();
            }
        }).show();
    }


}

Method 4:

To display this dialog, we have to use animation to implement it by right-clicking on the res folder and then clicking on new then android resource directory, create a folder named anim and right click on the code below on the anim folder Create an animation layout and paste the code as an image.

slide_up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
         android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="100%"
         android:interpolator="@android:anim/accelerate_interpolator"
        android:toXDelta="0"/>




</set>

slide_right

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%p" android:toXDelta="100%p"
    android:duration="500">

</trans

slide_left

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="100%p" android:toXDelta="0"
    android:duration="500"/>

MainActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;

public class MainActivity extends AppCompatActivity {
    private NiftyDialogBuilder materialDesignAnimatedDialog;
    private  Button btn1,btn2,btn3,btn4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View btnShowDialog = findViewById(R.id.btn1);
        View  btnShowDialog2 = findViewById(R.id.btn2);
        View  btnShowDialog3 = findViewById(R.id.btn3);
        View  btnShowDialog4 = findViewById(R.id.btn4);
        btnShowDialog.setOnClickListener(onClickListener(1));
        btnShowDialog2.setOnClickListener(onClickListener(2));
        btnShowDialog3.setOnClickListener(onClickListener(3));
        btnShowDialog4.setOnClickListener(onClickListener(4)); }
        private View.OnClickListener onClickListener(final int style)
        {
            return new View.OnClickListener()
            {
                @Override public void onClick(View v)
                {
                    if (style == 1)
                    {
                        buildDialog(R.style.DialogThemes, "Left - Right Animation!");
                    }
                    else if (style == 2)
                    { buildDialog(R.style.DialogAnimations, "Fade In - Fade Out Animation!"); }
                    else if (style == 3)
                    { buildDialog(R.style.DialogAnimations_2, "Up - Down Animation!"); }
                    else { buildDialog(0, "Normal Dialog (no animation)");
                    }
                }
            };
        }
        private void buildDialog(int animationSource, String type)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle("Animation Dialog"); builder.setMessage(type);
       builder.setNegativeButton("OK", null);
       AlertDialog dialog = builder.create(); dialog.getWindow().getAttributes().windowAnimations = animationSource; dialog.show();
    }
After pasting this code, you will get the error of the theme. To fix this error, you have to open the value folder and open the theme file, you will have to paste the below code in it and this error will be fixed.

theme

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

        <item name="colorPrimary">@color/purple_500</item>

        <item name="colorPrimaryDark">@color/purple_700</item>

        <item name="colorAccent">@color/purple_200</item>
    </style>

    <style name="DialogTheme">

        <item name="android:windowEnterAnimation">@anim/slide_left</item>

        <item name="android:windowExitAnimation">@anim/slide_right</item>
    </style>

    <style name="DialogAnimation">

        <item name="android:windowEnterAnimation">@android:anim/fade_in</item>

        <item name="android:windowExitAnimation">@android:anim/fade_out</item>
    </style>

    <style name="DialogAnimation_2">

        <item name="android:windowEnterAnimation">@anim/slide_up</item>

        <item name="android:windowExitAnimation">@anim/slide_bottom</item>
    </style>


    ////////Dialog Theme

    <style name="DialogThemes">
        <item name="android:windowEnterAnimation">@anim/slide_left</item>
        <item name="android:windowExitAnimation">@anim/slide_right</item>
    </style>

    <style name="DialogAnimations">
        <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
        <item name="android:windowExitAnimation">@android:anim/fade_out</item>
    </style>

    <style name="DialogAnimations_2">
        <item name="android:windowEnterAnimation">@anim/slide_up</item>
        <item name="android:windowExitAnimation">@anim/slide_bottom</item>
    </style>


And finally you can run this project and hope that this article will be very useful for you.Thanks .....

Post a Comment

0 Comments