我无法像大多数教程中那样创建新的自定义对话框。
public class MyDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("hi")
.setMessage("hello")
.setNeutralButton("ok", null)
.create();
}
}
现在我正在尝试创建一个新对象:
DialogFragment dialog = new MyDialog();
Android Studio向我展示:
需要DialogFragment,找到MyDialog
如何修复?
答案 0 :(得分:1)
我用它来创建一个真正的自定义对话框。
这需要称为 alert_dialog_view
的布局AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
View alertView = getLayoutInflater().inflate(R.layout.alert_dialog_view, null);
//Set the view
alert.setView(alertView);
//Show alert
final AlertDialog alertDialog = alert.show();
//OPTIONAL Can not close the alert by touching outside.
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
要创建标准对话框,您可以执行此操作...
public class DialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
});
// Create the AlertDialog object and return it
return builder.create();
}
}
}
答案 1 :(得分:1)
我尝试如下创建自定义对话框:
dialog.xml
中创建XML文件layout
,以设置对话框布局的布局和视图在您的活动文件中:
Dialog dialog = new Dialog(YourActivity.this);
dialog.setTitle("Your dialog title");
dialog.setContentView(R.layout.dialog);
dialog.show();
单击以设置对话框内的视图,例如:
Button btn = dialog.findViewById(R.id.btn_id);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
//Insert your code here
}
});