Alert Dialog in Android
In this tutorial we will learn how to create an Alert Dialog in Android with a simple example. Basically a Dialog is a small pop up window that prompts a user to make the decision.
Example:
- Create a new project as AlertDialog in Android Studio.
- Design a Button in activity_main.xml, as follows
<LinearLayout
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"
android:gravity="center"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.hss_24.alertdialog.MainActivity">
<Button
android:id="@+id/button"
android:text="Alert Dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
- Now we have to create a Alertdialog by using Builder and set the Positive and Negative Buttons respectively
- Do the following in MainActivity.java file.
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("CONFIRM DELETE");
builder.setMessage("Are you sure you want to delete");
builder.setCancelable(true);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
builder.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "Not deleted", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
- Now run the Application.
Download project here
Thank You!!!
Please like and share...
Checkout the new Smartphone by Le Eco, LetV Le 1s only with 10,999... Sale starts on 25 Feb 16
Comments
Post a Comment