AlertDialog

AlertDialog can be used to display message with Ok and Cancel buttons. It can be used to interrupt and ask the user about user's choice to continue or discontinue.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:text="Click" />
</RelativeLayout>


MainActvity
package com.example.alertdialog;

import android.app.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void onClick(View view) {

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to close this application?")
  .setCancelable(false)
  .setPositiveButton("Yes", new DialogInterface.OnClickListener()     {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            finish();
    }
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
  });

  AlertDialog alert = builder.create();

  alert.setTitle("AlertDialog");
  alert.show();
}
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is    present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
  }
}

Output:

                                                      After click





Source code:  AlertDialog.rar

Comments

Popular posts from this blog

SQLiteDatabase (Without SqliteOpenHelper class)

Set current date to Button and Datepicker dialog

MVC Architecture in Android