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:

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

        final Button btnSave;
        btnSave = findViewById(R.id.btnSpeichern_pdf);
        btnSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
  
                final EditText edittext = 
                    new EditText(activity_yourActivityName.this);
                    final ViewGroup.LayoutParams layoutParams = 
                    new ActionBar.LayoutParams(50, 30);
                    edittext.setGravity(Gravity.CENTER_HORIZONTAL);
                    edittext.setLayoutParams(layoutParams);
                    new AlertDialog.Builder(NameOfThisActivity.this)
                            //Bonus for userinput
                            .setView(edittext)
                            .setTitle("Save")
                            .setMessage("Wanne Save?")
                            .setPositiveButton("Save",
                             new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                int which) {
                                //your code when the user presses "Save"
                                }
                            })
                            .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, 
                                    int which) {
                                    Log.d("MainActivity", "Aborting Save");
                                    //your Code when the user presses "Cancel"
                                }
                            })
                        	.show();
    		}
		});
	}

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 *