无法创建新的自定义对话框

时间:2018-07-06 12:39:00

标签: java android

我无法像大多数教程中那样创建新的自定义对话框。

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

如何修复?

2 个答案:

答案 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)

我尝试如下创建自定义对话框:

  1. 在文件夹dialog.xml中创建XML文件layout,以设置对话框布局的布局和视图
  2. 在您的活动文件中:

     Dialog dialog = new Dialog(YourActivity.this);
     dialog.setTitle("Your dialog title");
     dialog.setContentView(R.layout.dialog);
     dialog.show();
    
  3. 单击以设置对话框内的视图,例如:

     Button btn = dialog.findViewById(R.id.btn_id);
     btn.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) 
       {
         //Insert your code here
       }
     });