Android Basic Training Course: Showing Pop-up Messages

    Sometimes, your activity (or an similar code) will need to speak up. Not every interaction with users of Android are neatly organized in the activity. The error appears, the background task will take longer than expected, some things asynchronously can occur, such as a message,... In these cases, you might need to communicate with users outside the boundaries of the traditional user interface.
    In this post, you'll learn two methods to make the pop-up message: Toast and AlertDialog. Moreover, Android also has some other methods that allows you to send notifications to the user without showing the Activity. In particular, the form of reminders (notifications), attached to the intent, or a similar service, they will be introduced in the following chapters.
DEMO VIDEO:

Showing Toast Messages


    A Toast is a view containing a quick little message for the user. So, this mean it will show after invoke it (for example, clicking a Button) and dissapear automatically after a period times. Look at this simple code to show a Toast:
 Toast.makeText(this, "This is a Toast message!", Toast.LENGTH_SHORT).show();
    As you can see, creating a Toast by call makeText() method with params:
- Current Context: usually is the current Activity - can be replace by "this".
- Message: a custom message written by developer!
- Duration: usally we use 2 default values: Toast.LENGTH_SHORT or Toast.LENGTH_LONG depending on the length of time you want it displayed.
   And we have this output interface: a white text line in front of dark background shape:
    Note: By setView() method in Toast class, you can make a custom view for it. But, by the aim is showing a notice in a period of times, this action seem not to be popular. In further way, you can use an external libary called Crouton to make a custom Toast with some exciting styles, please see my previous post about it!

Showing Alert Dialogs

    If you want to use dialog box with the classic style then what you need is to use class AlertDialog. Like any other forms of the dialog box, a AlertDialog layout will appear, take away the focus, and stay in there until the user closes it again. You can use it for critical error, a confirming message that effectively can not display in the user interface of basic activity, or some other situations where you are certain that users need to see it immediately.
    The easiest way to build a class AlertDialog using Builder. According this way, Builder provides a variety of methods for configuring a AlertDialog. Finally, calling show() on the builder to display the dialog.
    And the follow code is use for display a AlertDialog with 2 Buttons:
AlertDialog.Builder builder = new AlertDialog.Builder(this);

            //Set title for AlertDialog
            builder.setTitle("Dialog with 2 Buttons");

            //Set body message of Dialog
            builder.setMessage("See Android tuts at DevExchanges.info");

            //// Is dismiss when touching outside?
            builder.setCancelable(true);

            //Positive Button and it onClicked event listener
            builder.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Toast.makeText(MainActivity.this, "Positive Button clicked!", Toast.LENGTH_SHORT).show();
                        }
                    });

            //Negative Button
            builder.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //Usually, negative use to close Dialog
                            //So, do nothing here, just dismiss it
                        }
                    });

            AlertDialog dialog = builder.create();
            dialog.show();
    With AlertDialog, when you click at any Button, the dialog is closed. Usally, with this "2 Buttons" style, we hadle clicked event for Positive Button, and do nothing when Negative Button clicked (just close the dialog)! This usally use for confirming action.
    Output (in Lollipop device):
    Of course, in above code, if you remove builder.setPositiveButon() code, you will have a Dialog with sinle Button. It's used in showing a error or notice message:
    We can also add a Neutral Button to AlertDialog layout by this code:
            //Neutral Button
            builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Usually, negative use to close Dialog. So, do nothing here, just dismiss it
                    Toast.makeText(MainActivity.this, "Neutral Button clicked!", Toast.LENGTH_SHORT).show();
                }
            });
    By default design, AlertDialog has maximum 3 Buttons:

Full Demo Project code

    Finally, I provide full code for this demo project. It's include only 1 Activity and showing Pop-up messages by clicking the Buttons. Activity programmatically code:
package devexchanges.info.androidpopupmessages;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnSingle;
    private Button btnMultiple;
    private Button btn3Alert;
    private Button btnToast;

    private void findViews() {
        btnSingle = (Button) findViewById(R.id.btn_single);
        btnMultiple = (Button) findViewById(R.id.btn_multiple);
        btn3Alert = (Button) findViewById(R.id.btn_3_alert);
        btnToast = (Button) findViewById(R.id.btn_toast);

        btnSingle.setOnClickListener(this);
        btnMultiple.setOnClickListener(this);
        btn3Alert.setOnClickListener(this);
        btnToast.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btnMultiple) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            //Set title for AlertDialog
            builder.setTitle("Dialog with 2 Buttons");

            //Set body message of Dialog
            builder.setMessage("See Android tuts at DevExchanges.info");

            // Is dismiss when touching outside?
            builder.setCancelable(true);

            //Positive Button and it onClicked event listener
            builder.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Toast.makeText(MainActivity.this, "Positive Button clicked!", Toast.LENGTH_SHORT).show();
                        }
                    });

            //Negative Button
            builder.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //Usually, negative use to close Dialog
                            //So, do nothing here, just dismiss it
                        }
                    });

            AlertDialog dialog = builder.create();
            dialog.show();
        }
        else if (v == btnSingle) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            //Set title for AlertDialog
            builder.setTitle("Dialog with 1 Buttons");

            //Set body message of Dialog
            builder.setMessage("See Android tuts at DevExchanges.info");

            //// Is dismiss when touching outside?
            builder.setCancelable(true);

            //Negative Button
            builder.setNegativeButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //Usually, negative use to close Dialog
                            //So, do nothing here, just dismiss it
                        }
                    });

            AlertDialog dialog = builder.create();
            dialog.show();
        } else if (v == btn3Alert) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            //Set title for AlertDialog
            builder.setTitle("Dialog with 3 Buttons");

            //Set body message of Dialog
            builder.setMessage("See Android tuts at DevExchanges.info");

            //// Is dismiss when touching outside?
            builder.setCancelable(true);

            //Positive Button and it onClicked event listener
            builder.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //Invoke Positive event
                            Toast.makeText(MainActivity.this, "Positive Button clicked!", Toast.LENGTH_SHORT).show();
                            btn3Alert.setText("Showed!"); //change Button Text
                        }
                    });

            //Negative Button
            builder.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //Usually, negative use to close Dialog. So, do nothing here, just dismiss it
                            Toast.makeText(MainActivity.this, "Negative Button clicked!", Toast.LENGTH_SHORT).show();
                        }
                    });

            //Neutral Button
            builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Usually, negative use to close Dialog. So, do nothing here, just dismiss it
                    Toast.makeText(MainActivity.this, "Neutral Button clicked!", Toast.LENGTH_SHORT).show();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();
        } else if (v == btnToast) {
            Toast.makeText(this, "This is a Toast message!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
    }
}
    And it's layout:

Conclusions & References

    In this chapter, I've present the way to show a Pop-up message in Android by Toast and AlerDialog. In this project, I have not custom any thing in their layout, you can find out the solution to make a AlertDialog with EditText, a Toast with custom layout,...to deep understanding this topic.  Thanks for reading!
Official docs:
- Toasthttp://developer.android.com/intl/vi/reference/android/widget/Toast.html
- AlertDialoghttp://developer.android.com/intl/vi/reference/android/app/AlertDialog.html




Previous Chapter

Share


Previous post
« Prev Post
Next post
Next Post »