0

I can't create new custom dialog like in most tutorials.

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();
    }
}

and now I'm trying create a new object:

DialogFragment dialog = new MyDialog();

Android studio show me:

required DialogFragment, found MyDialog

How to fix it ?

androidmanifest
  • 289
  • 1
  • 4
  • 9

2 Answers2

1

I use this to create a true custom dialog box.

This requires a layout called 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));

To create a standard dialog box, you can do this...

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();
      }
   }
}
letsCode
  • 2,774
  • 1
  • 13
  • 37
0

I have tried as follow to create a custom dialog:

  1. Create XML file dialog.xml in folder layout to set layout and views for your dialog layout
  2. In your activity file:

     Dialog dialog = new Dialog(YourActivity.this);
     dialog.setTitle("Your dialog title");
     dialog.setContentView(R.layout.dialog);
     dialog.show();
    
  3. set on click for the views inside your dialog, example:

     Button btn = dialog.findViewById(R.id.btn_id);
     btn.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) 
       {
         //Insert your code here
       }
     });
    
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30