Java 如何在自定义android对话框中设置按钮?

Java 如何在自定义android对话框中设置按钮?,java,android,android-alertdialog,Java,Android,Android Alertdialog,我需要为自定义对话框设置正按钮和负按钮 public void newVisitorDialog(String title, String msg) { Dialog visitorDialog = new Dialog(FindVisitorMobile.this); visitorDialog.setCanceledOnTouchOutside(true); visitorDialog.setContentView(R.layout.new_visitor_

我需要为自定义对话框设置正按钮和负按钮

    public void newVisitorDialog(String title, String msg) {
    Dialog visitorDialog = new Dialog(FindVisitorMobile.this);
    visitorDialog.setCanceledOnTouchOutside(true);

    visitorDialog.setContentView(R.layout.new_visitor_dialog);
    TextView titleText = visitorDialog.findViewById(R.id.title);
    titleText.setText(title);
    TextView body = visitorDialog.findViewById(R.id.visitorData);
    body.setText(msg);
    visitorDialog.show();
}
谢谢,

请执行以下操作:

// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
       .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // FIRE ZE MISSILES!
           }
       })
       .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // User cancelled the dialog
           }
       });
// Create the AlertDialog object and return it
return builder.create();

对于自定义对话框,您应该在
R.layout.new\u dialog\u visitor
中包含这两个按钮


然后在您的
newvisitor对话框
方法中,找到带有
.findViewById
的按钮,并在其上调用
.setOnClickListener(…)

在Xml布局中添加负按钮和正按钮

找到按钮的视图

将setOnClickListener设置为负值和正值按钮

    Button negative = (Button) visitorDialog.findViewById(R.id.negative_btn);
    Button positive = (Button) visitorDialog.findViewById(R.id.positive_btn);

    negative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //process your code here for negative
        }
    });

   positive.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //process your code here for positive
        }
    });

如果是自定义对话框,您可以为其创建一个完整的另一个布局
这里有一个
它展示了如何在对话框中添加按钮、文本视图和图像。希望对您有所帮助。

我发现最好的方法是将对话框设置为类中的私有变量

    private Dialog visitorDialog;
public void newVisitorDialog(String title, String msg) {
    visitorDialog = new Dialog(FindVisitorMobile.this);
    visitorDialog.setCanceledOnTouchOutside(true);

    visitorDialog.setContentView(R.layout.new_visitor_dialog);
    TextView titleText = visitorDialog.findViewById(R.id.title);
    titleText.setText(title);
    TextView body = visitorDialog.findViewById(R.id.visitorData);
    body.setText(msg);
    visitorDialog.show();
}

/**
 * Cancel the visitor dialog
 * @param view
 */
public void dialogCancel(View view){
    visitorDialog.dismiss();
}

谢谢,这种方法也适用于我。如果有效,请将此答案标记为已接受