: Beginning Android

Checking Them Out

Checking Them Out

To see how these work in practice, take a peek at Messages/Message (available from the Source Code section of the Apress Web site), containing the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" >
android:text="Raise an alert"
android:text="Make a toast"

and the following Java code:

publicclass MessageDemoextends Activityimplements View.OnClickListener {
Button alert;
Button toast;
public voidonCreate(Bundle icicle) {
alert = (Button)findViewById(R.id.alert);
toast = (Button)findViewById(R.id.toast);
public voidonClick(View view) {
if (view==alert) {
new AlertDialog.Builder(this)
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing it will close on its own
}else {
.makeText(this, "<clink, clink>", Toast.LENGTH_SHORT)

The layout is unremarkable just a pair of buttons to trigger the alert and the Toast.

When the Raise an Alert button is clicked, we use a builder (new Builder(this)) to set the title (setTitle("MessageDemo)"), message (setMessage("eek!")), and neutral button (setNeutralButton(Close, new OnClickListener() ...) before showing the dialog. When the button is clicked, the OnClickListener callback does nothing; the mere fact the button was pressed causes the dialog to be dismissed. However, you could update information in your activity based upon the user action, particularly if you have multiple buttons for the user to choose from. The result is a typical dialog box like the one in Figure 14-1.

Figure 14-1.The MessageDemo sample application, after clicking the Raise an Alert button

When you click the Make a Toast button, the Toast class makes us a text-based Toast(makeText(this, "<clink, clink>", LENGTH_SHORT)), which we then show(). The result is a short-lived, non-interrupting message (see Figure 14-2).

Figure 14-2.The same application, after clicking the Make a Toast button

: 1.051. /Cache: 3 / 1