I have a button and I would like to open a dialog when pressed. This is my code:
Button more = (Button) findViewById(R.id.more); more.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //Intent myIntent = new Intent(view.getContext(), agones.class); //startActivityForResult(myIntent, 0); AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("hi"); alertDialog.setMessage("this is my app"); alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // here you can add functions } }); } });
OnClickListener() { public void onClick(View view) { //Intent myIntent = new Intent(view. getContext(), agones. class); //startActivityForResult(myIntent, 0); AlertDialog alertDialog = new AlertDialog. Builder(this).
setButton(int whichButton, CharSequence text, Message msg) − It is used to set button for alert dialog as shown below example. getListView() − it is used to get a list view which is used inside alert dialog.
A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
If you wish to prevent a dialog box from closing when one of these buttons is pressed you must replace the common button handler for the actual view of the button. Because it is assigned in OnCreate(), you must replace it after the default OnCreate() implementation is called.
As @Roflcoptr has said, you haven't called alertDialog.show()
method. thus your dialog doesn't appear.
Here's your edited code:
Button more = (Button) findViewById(R.id.more); more.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //Intent myIntent = new Intent(view.getContext(), agones.class); //startActivityForResult(myIntent, 0); AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update alertDialog.setTitle("hi"); alertDialog.setMessage("this is my app"); alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // here you can add functions } }); alertDialog.show(); //<-- See This! } });
if you write this
instead of <ActivityName>.this
, then it is going to take the reference of View.OnClickListener
since this
is currently being accessed inside it. You need to give your Activity's name there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With