When I say dialogs, I mean the little alert window that pops up and lets you know about an error that occurred or warns you about something you can’t do. It locks up the whole screen and demands you pay attention to it. I use a dialog to display information about the application.
Android has a few type of alert dialogs. One is a dialog that will not go away unless you make it go away. The other is a dialog that goes away after soem time. We will take a look at both of them here.
First, let’s look at dialogs that don’t go away unless you tell them to. Here is the code for them :
public class SomeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstance) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(“This is an alert with no consequence”);
dlgAlert.setTitle(“App Title”);
dlgAlert.setPositiveButton(“OK”, null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
}
The code above will display an alert with a title, a message and an OK button at the bottom. You don’t really have to set the title, the ok button or the message but it helps to do so. If you don’t use an “OK” (or whatever) button, the dialog will never go. The user will have to close the application in order to get out of it. There are other types of buttons that you can use (and you can use multiple buttons also). You can take a look at AlertDialogBuilder’s API for more information here.
The second type of dialog is more of a notification alert that is displayed on the main screen. I have used it before in my previous post which spoke about how to set alarms in Android. This alert will be shown for some time and regardless of whether a user responds to it or not, it will disappear after some time. Below is the code that is used to call it (or display it) :
Toast.makeText(con, “This is a message from hell. Yes my friend, HELL”, Toast.LENGTH_SHORT).show();
The above code will display an alert for a short amount of time and then close it. This alert is very simple and short and doesn’t require much to be displayed. You can also use Toast.LENGTH_LONG to display the alert for a longer period of time. And, like always below are the screenshots of what both of them look like.
Leave a Reply