AlertDialog

Droid By Me
1 min readDec 29, 2017

--

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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Output:

--

--

Droid By Me
Droid By Me

Written by Droid By Me

By profession and passion : Android Developer

No responses yet