JoeyCK
JoeyCK

Reputation: 1402

Add positive button to Dialog

I have a very simple custom dialog and I wan't to add a positive button without having to modify the XML file, just like you would do it with an AlertDialog but I don't know if it's possible. This is the code:

final Dialog dialog = new Dialog(MyActivity.this);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Settings");
dialog.show();

Upvotes: 9

Views: 25573

Answers (3)

amp
amp

Reputation: 12352

You should use the builder.

LayoutInflater inflater = LayoutInflater.from(this);
View dialog_layout = inflater.inflate(R.layout.dialog,(ViewGroup) findViewById(R.id.dialog_root_layout));
AlertDialog.Builder db = new AlertDialog.Builder(MyActivity.this);
db.setView(dialog_layout);
db.setTitle("settings");
db.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    }
});
AlertDialog dialog = db.show();

Upvotes: 14

Atiar Talukdar
Atiar Talukdar

Reputation: 746

You also can use this function

public void showMessage(String title,String message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton("OK", new
            DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
    builder.show();
}

Upvotes: 1

MattDavis
MattDavis

Reputation: 5178

You can use the AlertDialog.Builder class:

http://developer.android.com/reference/android/app/AlertDialog.Builder.html

Create a new instance of it with AlertDialog.Builder myAlertDialogBuilder = new AlertDialog.Builder(context). Then use methods such as setTitle() and setView() to customize it. This class also has methods for setting the buttons. setPositiveButton(String, DialogInterface.OnClickListener) to set up your buttons. Finally, use AlertDialog myAlertDialog = myAlertDialogBuilder.create() to get your instance of AlertDialog, which you can then further customize with methods such as setCancelable().

Edit: Also, from the docs: http://developer.android.com/guide/topics/ui/dialogs.html

"The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dialog directly. Instead, you should use one of the... subclasses"

If you really don't want to use an AlertDialog, it'll probably be best to extend the Dialog class yourself, rather than using it as-is.

Upvotes: 2

Related Questions