Hrnsvnc Blog

Software, Technology and stuff


How to create an AlertDialog with AlertDialog.Builder for android in Java

In this short Example i will show you how to create an AlertDialog in Android with the AlerDialog.Builder in Java for your android App.

First of all the code you need:

    protected void onCreate(Bundle savedInstanceState) {

        final Button btnSave;
        btnSave = findViewById(;
        btnSave.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                final EditText edittext = 
                    new EditText(activity_yourActivityName.this);
                    final ViewGroup.LayoutParams layoutParams = 
                    new ActionBar.LayoutParams(50, 30);
                    new AlertDialog.Builder(NameOfThisActivity.this)
                            //Bonus for userinput
                            .setMessage("Wanne Save?")
                             new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                int which) {
                                //your code when the user presses "Save"
                                new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, 
                                    int which) {
                                    Log.d("MainActivity", "Aborting Save");
                                    //your Code when the user presses "Cancel"

Put that code inside of your OnCreate Method inside your activity. In this example I try to crate a button (btnSave). After clicking on it there should appear a dialog window that asks you something. I can choose weather i “Save” or “Cancel” my action.

You may noticed my comment on line 17/18. I am adding an edditText by using the “.setView” method. I simply add some edittext field to get some userinput. After that i could do some stuff in the “OnClick” method of the “Save” button.

I hope i could help you out with some magic.

Please follow and like us:
Tweet 20

Leave a Reply

Your email address will not be published. Required fields are marked *