Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be used to interrupt and ask the user about his/her choice to continue or discontinue.
Android AlertDialog is composed of three regions: title, content area and action buttons.
Android AlertDialog is the subclass of Dialog class.
Android AlertDialog Example
Let's see a simple example of android alert dialog.
activity_main.xml
You can have multiple components, here we are having only a textview.
File: activity_main.xml
- <RelativeLayout xmlns:androclass="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" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:text="@string/hello_world" />
-
- </RelativeLayout>
strings.xml
Optionally, you can store the dialog message and title in the strings.xml file.
File: strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <string name="app_name">alertdialog</string>
- <string name="hello_world">Hello world!</string>
- <string name="menu_settings">Settings</string>
- <string name="dialog_message">Welcome to Alert Dialog</string>
-
- <string name="dialog_title">Alert Dialog</string>
- </resources>
Activity class
Let's write the code to create and show the AlertDialog.
File: MainActivity.java
- package com.example.alertdialog;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.view.Menu;
-
- public class MainActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
-
-
-
-
- builder.setMessage("Do you want to close this application ?")
- .setCancelable(false)
- .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- finish();
- }
- })
- .setNegativeButton("No", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
-
- dialog.cancel();
- }
- });
-
-
- AlertDialog alert = builder.create();
-
- alert.setTitle("AlertDialogExample");
- alert.show();
- setContentView(R.layout.activity_main);
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
-
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
-
- }
Output:
simply defined concept
ReplyDelete