Android Custom Dialog and AlertDialog that Prompts User to Make Decision

Dialog

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

AlertDialog

Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog.

In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Step 1: Open Android Studio.

Step 2: Create a new project as follows:

If you see the Welcome to Android Studio dialog, choose Start a new Android Studio project, available under ‘Quick Start’ on the right of the dialog.
Otherwise, click File in the Android Studio menu bar, then New, New Project.
Step 3: Enter your app name, company domain, and project location, as prompted. Then click Next.

Step 4: Select the form factors you need for your app. If you’re not sure what you need, just select Phone and Tablet. Then click Next.

Step 5: Select Empty Activity in the ‘Add an activity to Mobile’ dialog. Then click Next.

Step 6: Enter the activity name, layout name and title as prompted. The default values are fine. Then click Finish.

After that wait for few seconds. Android Studio starts Gradle and builds of your project.

Step 7: Now do some changes in your MainActivity.xml file. Add new TextView control in xml file.

<TextView android:id="@+id/txtMsg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textColor="@color/colorPrimary"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Step 8: Create a object of TextView control in onCreate() method.

private TextView txtMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtMsg = (TextView) findViewById(R.id.txtMsg);

    txtMsg.setText("Hello Friends!\n This is My Sample project of Android AlertDialog");
}

Step 9: In your MainActivity.java file do following code onBackpressed() method.

@Override
public void onBackPressed(){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Confirm");
    builder.setMessage("Are you sure to go back?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    builder.show();
}

Step 10: Now you can run your code and check while you press back button a alertdialog will appears to confirmation.

Step 11: Now create a custom dialog to update txtMsg text. create a private method which create a custom dialog box.

protected void showDialog(final TextView text){

    LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
    View promptView = layoutInflater.inflate(R.layout.updatedialogitem,null);
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setView(promptView);
    builder.setTitle("Update Text");

    final EditText updText = (EditText) promptView.findViewById(R.id.updTxt);

    builder.setCancelable(false).setPositiveButton("Update", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            text.setText(updText.getText().toString());
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();

}

Step 11: Add layout file with follow following steps:

res -> layout -> right click – new layout resource file

Give name in small character updatedialogitem.xml.

Step 11: Do Following changes in onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtMsg = (TextView) findViewById(R.id.txtMsg);

    txtMsg.setText("Hello Friends!\n This is My Sample project of Android AlertDialog");

    txtMsg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showDialog(txtMsg);
        }
    });

}

Step 12: Now you can run your code and check.

Full Source Code

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.suraj.alertdialogsample.MainActivity">

    <TextView android:id="@+id/txtMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.example.suraj.alertdialogsample;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    private TextView txtMsg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtMsg = (TextView) findViewById(R.id.txtMsg);

        txtMsg.setText("Hello Friends!\n This is My Sample project of Android AlertDialog");

        txtMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(txtMsg);
            }
        });

    }

    protected void showDialog(final TextView text){

        LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
        View promptView = layoutInflater.inflate(R.layout.updatedialogitem,null);
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setView(promptView);
        builder.setTitle("Update Text");

        final EditText updText = (EditText) promptView.findViewById(R.id.updTxt);

        builder.setCancelable(false).setPositiveButton("Update", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                text.setText(updText.getText().toString());
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();

    }

    // Creating Alert dialog for confirmation on back press //
    @Override
    public void onBackPressed(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirm");
        builder.setMessage("Are you sure to go back?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                MainActivity.super.onBackPressed();
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        builder.show();
    }
}

updatedialogitem.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.LinearLayoutCompat
        xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
        android:layout_height="match_parent" android:orientation="vertical">

        <TextView android:id="@+id/lblMsg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Fill New Text Below to Update Text Message."/>

        <EditText android:id="@+id/updTxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>


    </android.support.v7.widget.LinearLayoutCompat>

</android.support.constraint.ConstraintLayout>

 

Post a comment

Your email address will not be published. Required fields are marked *