【问题标题】:How set buttons in custom android dialog? [duplicate]如何在自定义 android 对话框中设置按钮? [复制]
【发布时间】:2018-09-26 06:41:30
【问题描述】:
我需要为自定义对话框设置正负按钮。
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();
}
谢谢,
【问题讨论】:
标签:
java
android
android-alertdialog
【解决方案1】:
在 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
}
});
【解决方案2】:
这样做:
// 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();
【解决方案3】:
对于自定义对话框,您应该在R.layout.new_dialog_visitor 中包含这两个按钮。
然后在您的newVisitorDialog 方法中找到带有.findViewById 的按钮并在它们上调用.setOnClickListener(..)。
【解决方案4】:
如果它是一个自定义对话框,您可以为其创建一个全新的布局
这是link
它展示了如何向对话框添加按钮、文本视图、图像。希望对您有所帮助
【解决方案5】:
我发现最好的方法是将对话框设置为类中的私有变量。
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();
}