Search code examples
androidmaterial-uimaterial-components-androidmaterial-components

Material Design 3 DialogFragment is not styled like Dialogs using MaterialAlertDialogBuilder


I have migrated migrated to Material Design 3 and notice that the DialogFragments are not styled like dialogs created using MaterialAlertDialogBuilder. Do you need to add customized styling to DialogFragments? I thought it should work out of the box. What I notice is that DialogFragments do not have rounded corners, and surface color doesn't match dialogs you create using MaterialAlertDialogBuilder. I'm using DialogFragment in the cases where I need a custom view and cannot use MaterialAlertDialogBuilder. So how would I style it to look like a MaterialAlertDialog?


Solution

  • Found the solution here https://dev.to/bhullnatik/how-to-use-material-dialogs-with-dialogfragment-28i1

    Here's the sample code where you need to overwrite onCreateDialog and use the standard MaterialAlertDialogBuilder

    public class YourSexyMaterialDialogFragment extends DialogFragment {
    
      View theDialogView;
    
      @Override
      public Dialog onCreateDialog(Bundle savedInstanceState) {
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
        theDialogView = onCreateView(LayoutInflater.from(requireContext()), null, savedInstanceState);
        builder.setView(theDialogView);
    
        return builder.create();
      }
    
      @Override
      public View getView() {
          return theDialogView;
      }
    
      @Override
      public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
        // remains the same where you inflate your custom view and setup ui components
      }  
    
    }