Книга: 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:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" >
 <Button
  android:id="@+id/alert"
  android:text="Raise an alert"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>
 <Button
  android:id="@+id/toast"
  android:text="Make a toast"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>
</LinearLayout>

and the following Java code:

public class MessageDemo extends Activity implements View.OnClickListener {
 Button alert;
 Button toast;
 @Override
 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.main);
  alert = (Button)findViewById(R.id.alert);
  alert.setOnClickListener(this);
  toast = (Button)findViewById(R.id.toast);
  toast.setOnClickListener(this);
 }
 public void onClick(View view) {
  if (view==alert) {
   new AlertDialog.Builder(this)
    .setTitle("MessageDemo")
    .setMessage("eek!")
    .setNeutralButton("Close", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dlg, int sumthin) {
     // do nothing – it will close on its own
    }
   })
   .show();
  } else {
   Toast
   .makeText(this, "<clink, clink>", Toast.LENGTH_SHORT)
   .show();
  }
 }
}

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.103. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз