time

How-to create AlertDialog in Android

Simple note about AlertDialog in Android. I'll show how to create simple dialog and custom dialog from layout using XML.

Simple AlertDialog

Main goal of AlertDialog is to provide information to user or to get some input from the user.

Let's start from describing main activity layout main_activity.xml.

<RelativeLayout 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" 
tools:context=".MainActivity" >

<Button android:id="@+id/btnShow" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerHorizontal="true" 
android:layout_centerVertical="true" 
android:text="Show AlertDialog" />
</RelativeLayout>

Describe our onCreate method and dialog creation method.

public class MainActivity extends Activity {   
    Button btnShow;

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main);   
        btnShow = (Button) findViewById(R.id.btnShow);
        btnShow.setOnClickListener(new View.OnClickListener() {   
            @Override public void onClick(View v) { 
                showDialog(); 
            } 
        }); 
    }   

    public void showDialog() { 
        AlertDialog.Builder alert = new AlertDialog.Builder(this); 
        alert.setTitle("Hello"); 
        alert.setMessage("Hello world!"); 
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {   
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
                dialog.dismiss(); 
            } 
        }); 
        AlertDialog dialog = alert.create(); 
        dialog.show(); 
    } 
}
Android simple AlertDialog

Here is example where our information dialog transforms to confirm dialog.

public void showDialog() { 
    AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    alert.setTitle("The question"); 
    alert.setMessage("To be or not to be?");
    alert.setCancelable(false);
    alert.setNegativeButton("Not to be", new DialogInterface.OnClickListener() {   
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
            Toast.makeText(getBaseContext(), "Not to be", Toast.LENGTH_SHORT).show(); 
        } 
    });   
    alert.setPositiveButton("To be", new DialogInterface.OnClickListener() {   
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
            Toast.makeText(getBaseContext(), "To be", Toast.LENGTH_SHORT).show(); 
        } 
    }); 
    AlertDialog dialog = alert.create(); 
    dialog.show(); 
}

AlertDialog with custom layout

Finally, we are going to create dialog with custom layout. The activity_main.xml is the same. In layout we'll use EditText, Spinner, DataPicker, CheckBox.

Bellow is layout_custom_dialog.xml with custom layout for our dialog.

<?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="match_parent"
    android:orientation="vertical"
    android:padding="15dp" >

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dip"
            android:layout_weight=".3"
            android:layout_height="wrap_content"
            android:text="Name:"
            />

        <EditText android:id="@+id/etName"
            android:layout_width="0dip"
            android:layout_weight=".7"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:imeOptions="actionDone" />
    </LinearLayout>

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView android:layout_width="0dip"
            android:layout_weight=".3"
            android:layout_height="wrap_content"
            android:text="Sex:"
            />

        <Spinner android:id="@+id/spSex"
            android:layout_width="0dip"
            android:layout_weight=".7"
            android:layout_height="wrap_content"
            android:entries="@array/sex_array"
            android:prompt="@string/sex_prompt" />
    </LinearLayout>

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dip"
            android:layout_weight=".3"
            android:layout_height="wrap_content"
            android:text="Birthday:"
            />

        <EditText android:id="@+id/etDate"
            android:layout_weight=".5"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:hint="Bithday"
            android:inputType="date" />

        <ImageButton android:id="@+id/btnDate"
            android:layout_width="0dip"
            android:layout_weight=".2"
            android:layout_height="wrap_content"
            android:onClick="selectDate"
            android:src="@drawable/abc_ic_go" />
    <LinearLayout>

    <CheckBox android:id="@+id/cbHungry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Is hungry?" />

</LinearLayout>

MainActivity stay the same, we gonna change only showDialog.

public void showDialog() {
    LayoutInflater inflater = getLayoutInflater();
    View alertLayout = inflater.inflate(R.layout.custom_layout_dialog, null);
    final EditText etName = (EditText) alertLayout.findViewById(R.id.etName);
    final EditText etDate = (EditText) alertLayout.findViewById(R.id.etDate);
    final CheckBox cbHungry = (CheckBox) alertLayout.findViewById(R.id.cbHungry);
    final Spinner spSex = (Spinner) alertLayout.findViewById(R.id.spSex);
    final ImageButton btnDate = (ImageButton) alertLayout.findViewById(R.id.btnDate);

    class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), this, yy, mm, dd);
        }

        public void onDateSet(DatePicker view, int yy, int mm, int dd) {
            etDate.setText((mm + 1) + "/" + dd + "/" + yy);
        }
    }

    btnDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = new SelectDateFragment();
            newFragment.show(getSupportFragmentManager(), "DatePicker");
        }
    });

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Form");
    alert.setView(alertLayout);
    alert.setCancelable(false);
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
        }
    });

    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String user = etName.getText().toString();
            String bday = etDate.getText().toString();
            String sex = String.valueOf(spSex.getSelectedItem());
            String hungry = (cbHungry.isChecked()) ? "Yes" : "No";
            Toast.makeText(getBaseContext(), "Name: " + user + "\nBirthday: " + bday + "\nSex: " + sex + "\nHungry: " + hungry, Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog dialog = alert.create();
    dialog.show();
}
Android simple AlertDialog

To add an icon to the dialog, use the setIcon() method. Here is an example

.setIcon(R.mipmap.ic_launcher)

Full code you can see at github.

AlertDialog with list

Also we can pass list to AlertDialog and do something on click

public class MainActivity extends AppCompatActivity {
    String[] movies = {"The Shawshank Redemption", "The Godfather", "The Dark Knight"};
    ...
    public void showDialog() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("IMDb Top 250");

        alert.setItems(movies, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getBaseContext(), movies[item], Toast.LENGTH_SHORT).show();
            }
        });

        AlertDialog dialog = alert.create();
        dialog.show();
    }
}

Useful links

comments powered by Disqus