Android alerts tutorial
In this tutorial we will talk about Android dialog boxes and more specifically AlertDialog.
Like any modal dialog box, an AlertDialog opens itself, takes focus and stay on as long as the user does not close it. This type of display is therefore well suited to critical errors or any other information which must read by the user.
To create an AlertDialog, the easiest way is to use the Builder class, which provides a set of methods for configuring an AlertDialog. Each method returns the Builder to facilitate the chaining of calls. In the end, just call the show() method of the Builder Object to display the dialog box.
The most used configuration method of Builder are:
● setMessage () defines the "body" of the dialog from a simple text message. Its setting is a String or an identifier of a text resource.
● setTitle () and setIcon () to configure the text and / or icon that will appear in the title bar of the dialog box.
● setPositiveButton () setNeutralButton () and setNegativeButton () allow to indicate the buttons that appear at the bottom of the dialog box, their lateral location (respectively, left, center or right), their text and code that will be called when the user clicks the button.
Create a new project and in your main xml file put this code :
main.xml
<?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="Click to Show Alert"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And this is the java code:
package com.example.alertdialog; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity implements View.OnClickListener { Button alert; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); alert=(Button)findViewById(R.id.alert); alert.setOnClickListener(this); } @Override public void onClick(View arg0) { new AlertDialog.Builder(this) .setTitle("My Alert Dialog") .setMessage("Are you fine !") .setNeutralButton("close",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int sumthin) { } }) .show(); } }The result will be like this :
Commentaires
Enregistrer un commentaire
Your comment will be reviewed by moderators