How to create positive and negative buttons in custom dialogs

I want to create a custom dialog. So I create a "dialog_change" template and I open a dialog.

Dialog myDialog = new Dialog(Overview.this);
myDialog.setContentView(R.layout.dialog_change);
myDialog.setTitle("My Custom Dialog Title");
myDialog.show();

      

enter image description here

Now I want to add two buttons (one positive and one negative button), at the bottom. How can i do this?

+3


source to share


2 answers


I would just create my own custom class to model the AlertDialog, this way you can use your own layout without string binding. (There are some weird problems where you can't get rid of the frame entirely if you want a fully styled AlertDialog). Something like this, but you can expand this as fully as possible:



public class CustomDialog extends Dialog {
    private Button positive, negative;

    public CustomDialog(Context context) {
        super(context);
        initialize(context);
    }

    protected CustomDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        initialize(context);
    }

    public CustomDialog(Context context, int theme) {
        super(context, theme);
        initialize(context);
    }

    private void initialize(Context c) {
        //Inflate your layout, get a handle for the buttons

        positive = (Button)layout.findViewById(R.id.positive):
        negative = (Button)layout.findViewById(R.id.negative):

        positive.setVisibility(View.GONE);
        negative.setVisibility(View.GONE);
    }

    public void setPositiveButton(String buttonText, View.OnClickListener listener) {
        positive.setText(buttonText);
        positive.setOnClickListener(listener);
        positive.setVisibility(View.VISIBLE);
    }

    public void setNegativeButton(String buttonText, View.OnClickListener listener) {
        negative.setText(buttonText);
        negative.setOnClickListener(listener);
        negative.setVisibility(View.VISIBLE);
    }
}

      

+5


source


You can add two buttons to the custom layout you use for the dialog (i.e. dialog_change). And then you can access them after creating the dialog like this:



Dialog myDialog = new Dialog(Overview.this);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_change,null);
myDialog.setContentView(view);
myDialog.setTitle("My Custom Dialog Title");

Button button1 = (Button)view.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v){
        dialog.dismiss();
    }
});
//Similarly for the second button
myDialog.show();

      

+1


source







All Articles