How to Show Alert Dialog on Button Click in Android

In android app, alert dialog is used to notify users about some important information or obtain data from users.

The code snippet below is used to show alert dialog when a button is clicked.

It is the default alert dialog.

If you want to customize android alert dialog, I will suggest you read my previous post on how to create custom alert dialog in android

activity_alert_dialog_button.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    android:background="#ededed">

    <Button
    android:id="@+id/alert_dialog"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:layout_centerInParent="true"
    android:text="Show Alert"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:textSize="15sp"/>

</RelativeLayout>

AlertDialogButton.java

public class AlertDialogButtonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_dialog_button);

        Button alertDialogButton = (Button)findViewById(R.id.alert_dialog);
        alertDialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(AlertDialogButtonActivity.this);
                alertDialogBuilder.setTitle("Your Title");
                alertDialogBuilder.setMessage("Show message over here");
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });
    }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.