Wednesday 10 June 2015

Alert dialog box

No comments
Hello,today i want to explore a simple program about android Alert Dialog box to give a professional look for your app.This alert dialog box displays alerts to the users for get confirmation from the users.Let's go for coding with easy steps:

In alert dialog box we show:

Title: The title like "Are you sure to exit". (Optional)

Content: Displays the message to the user. It can be a string message or a list or custom layout.


Action Button(s): Define action on button like "Exit" , "Yes / No" , "Later" , "Cancel" etc.

CREATE NEW ANDROID PROJECT:

Step 1: Write code into activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/buttonAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Alert me" />
            

</LinearLayout>

Step 2: Write code into MainActivity.java

package dev.androidapplink.alertboxapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

final Context context = this;
// create variable
private Button button;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load control
button = (Button) findViewById(R.id.buttonAlert);

// create button listener
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);

// set title
alertDialogBuilder.setTitle("Are You Sure?");

// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();

// show it
alertDialog.show();

}

});

}


}

NOTE: No need any permission in AndroidManifest.xml

Step 3:Run Your Project:







No comments :

Post a Comment

Follow me Share