Creating Alert Dialogs in Android

Android supports various forms of dialogs. Dialogs include Alert Dialogs, Progress dialogs, time picker dialogs and extend support to custom dialogs. Alert dialogs are used to prompt user or show simple message of validation.

Let’s begin with Android Alert Dialogs and see how to implement it.

Design Alert Dialog

Alert dialogs commonly contains messages to display as a validation or prompt user for some action. You can use alert dialog builder class to construct alert dialog. Lets see what kind of actions can be added in Alert Dialog.

  • Prompt user to respond with positive or negative action.
  • Pick single or multiple item from list displayed in the dialog.
  • Display some information to the user
  • Select option to confirm from a set of options.

Alert Dialog Builder

Steps to create a dialog builder:

  • Create dialog builder object
  • Set title, message and other parameters like
  • Build dialog from builder object
  • Show dialog
    private void showAlertDialog(Context context, String title, String message){
        // Create dialog builder
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title).setMessage(message);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

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

            }
        });
        
        
        // Build dialog
        AlertDialog aDialog = builder.create();
        
        // Show dialog
        aDialog.show();
        
    }

Prompt message in alertdialog android

Design Prompt Dialog in XML

We can inflate  custom view instead of the default message view of Alert Dialog. Now let’s design own custom alert message layout in xml.

Create dialog view layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="8dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="This is a custom message"
        android:id="@+id/dialogMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/userInput"
        android:hint="Enter your name"
        />

</LinearLayout>

Create custom alert dialog using the same code and set view with new created view.

    private EditText mEditText;
    private void showCustomAlertDialog(Context context, String title){
        // Create dialog builder
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);

        LayoutInflater inflater = LayoutInflater.from(context);
        View customLayout = inflater.inflate(R.layout.prompt_dialog_layout, null);
        mEditText = customLayout.findViewById(R.id.userInput);
        builder.setView(customLayout);

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String userInputText = mEditText.getText().toString();
                Log.e("tag", "User entered:" + userInputText);
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });


        // Build dialog
        AlertDialog aDialog = builder.create();

        // Show dialog
        aDialog.show();
    }

Create custom alert dialog in android

Dialog Fragments

We will see now how to create alert dialog using Dialog Fragments. Alert dialog will be managed by a fragment as DialogFragment contains object of dialog.

Let’s check how we will implement the above alert dialog example with DialogFragments. Create a new class and extend it from DialogFragment. DialogFragment provides a function onCreateDialog which returns dialog.

package com.codeexa.com.dialogs;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */
public class CustomDialogFragment extends DialogFragment {
    private Context mContext;
    public static CustomDialogFragment newInstance(String title, String message) {
        // Required empty public constructor
        CustomDialogFragment f = new CustomDialogFragment();
        Bundle b = new Bundle();
        b.putString("title", title);
        b.putString("message", message);
        // Add bundle data in arguments
        f.setArguments(b);
        return f;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        Bundle b = getArguments();
        String title = b.getString("title");
        String message = b.getString("message");
        builder.setTitle(title).setMessage(message);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

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

            }
        });

        // Build and return dialog
        AlertDialog aDialog = builder.create();
        return aDialog;
    }
}

From the activity we can now call our dialog fragment.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               CustomDialogFragment.newInstance("Dialog Fragment", "Showing dialog in a fragment");
            }
        });
    }
}

Toast Messages

Toast is similar to alert dialog with a message. The difference is that toast do not have any user interaction and is displayed only for a short time before it hides away.

   private void showToast(Context context, String message) {

        // Create and display toast message
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }

Toast alert example in android

Toasts can be used outside activity as it takes any context to create alert. Therefore toast alerts can be displayed from services, receivers etc.

 

Leave a Reply