SoFunction
Updated on 2025-03-03

Summary of the usage examples of DialogFragment in Android development

This article describes the usage of DialogFragment in Android development. Share it for your reference, as follows:

background

Officially recommended AndroidDialogFragment Let's replaceDialog , can make it more reusable (reduced coupling) and better convenience (well handle screen flip situations).

There are two ways to create DialogFragment:

1. Overwrite itonCreateDialogMethod — ①
2. Overwrite itonCreateViewMethod — ②

Although both methods can achieve the same effect, they each have their own suitable application scenarios:

1. Method ①, generally used to create scenes that replace traditional Dialog dialog boxes, with simple UI and single functions.
2. Method ②, It is generally used to create scenes with pop-ups of complex content or full-screen display effects. The UI is complex and the functions are complex, and generally there are asynchronous operations such as network requests.

application

Basic usage

For method ①, create aDialog And return it:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
 //For style uniformity and compatibility, you can use the V7 package  builder = new (getActivity());
 // How to set the theme //  builder = new (getActivity(), );
 ("Notice:")
   .setMessage("Do you exit the app?")
   .setPositiveButton("Sure", null)
   .setNegativeButton("Cancel", null)
   .setCancelable(false);
   //(); // Cannot use the show() method here return ();
}

Of course, you can also use customizationView To create:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
  builder = new (getActivity());
 // How to set the theme //  builder = new (getActivity(), );
 LayoutInflater inflater = getActivity().getLayoutInflater(); 
 View view = (.fragment_dialog, null); 
 (view) 
 // Do Someting,eg: TextView tv = ();
 return ();
}

PS: CreateDialog There are many ways to use it, such as the following, which are slightly different when using it, so you need to pay attention to it yourself:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
 LayoutInflater inflater = getActivity().getLayoutInflater();
  View view = (.fragment_dialog, null);
 Dialog dialog = new Dialog(getActivity());
  // How to set the theme  // Dialog dialog = new Dialog(getActivity(), );
  (view);
  // Do Someting
 return dialog;
}

For method ②, and ordinaryFragment The usage is basically the same:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View rootView = (.fragment_dialog, container, false);
 // Do Someting
 return rootView;
}
/**
  * To set the theme, you need to call the setStyle() method in the onCreate() method.
  */
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
 (savedInstanceState);
 setStyle(DialogFragment.STYLE_NO_TITLE, );
}

Handle screen flip

If using traditionalDialog , we need to manually handle the screen flip, but useDialogFragment If so, we don't need to do anything.FragmentManager Will be managed automaticallyDialogFragment life cycle.

Untitle bar/full screen

In the basic usage, there are places where the code comments are set. Here are two methods to set up the untitled bar and implement full screen:

Untitle bar

For method ①:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
 LayoutInflater inflater = getActivity().getLayoutInflater();
 View view = (.fragment_dialog, null);
 Dialog dialog = new Dialog(getActivity(), );
  // Close the title bar, call setContentView() before (Window.FEATURE_NO_TITLE);
 (view);
 (true);
 return dialog;
}

For method ②:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
 (savedInstanceState);
 /**
  * The first parameter of setStyle() has four optional values:
  * STYLE_NORMAL|STYLE_NO_TITLE|STYLE_NO_FRAME|STYLE_NO_INPUT
  * where STYLE_NO_TITLE and STYLE_NO_FRAME can close the title bar
  * For the detailed use of each parameter, you can directly view the Android source code description
  */
 setStyle(DialogFragment.STYLE_NO_TITLE, );
}

Implement full screen (width/height full screen)

Most commonly used forms are as wide as the screen and are highly adaptable. Let’s look at the code directly:

Method ①:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
 LayoutInflater inflater = getActivity().getLayoutInflater();
 View view = (.fragment_dialog, null);
 Dialog dialog = new Dialog(getActivity(), );
 (Window.FEATURE_NO_TITLE);
 (view);
 (true);
 //Do something
  // Set the width to the screen width and close to the bottom of the screen Window window = ();
 ();
  wlp = ();
  = ;
  = .MATCH_PARENT;
   = .WRAP_CONTENT;
 (wlp);
 return dialog;
}

Line 12 of the code sets the background color of the window to be transparent, this step is necessary;

Code Line 15 sets the width of the window toMATCH_PARENT,The effect is as large as the screen width, and you can also set the height value. Set width and height in addition toMATCH_PARENTandWRAP_CONTENT, can also be set directly to specific values.

Method ②:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
 (savedInstanceState);
 setStyle(DialogFragment.STYLE_NO_TITLE, );
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    getDialog().setCanceledOnTouchOutside(true);
    View rootView = (.fragment_dialog, container, false);
    //Do something
    // Set the width to the screen width, close to the bottom of the screen.    final Window window = getDialog().getWindow();
    ();
    ().setPadding(0, 0, 0, 0);
     wlp = ();
     = ;
     = .MATCH_PARENT;
     = .WRAP_CONTENT;
    (wlp);
    return rootView;
}

Line 14 of the code sets the background color of the window to be transparent, this step is necessary;

Line 15 of the code sets that the Pading values ​​of the window are all 0. This step is also necessary. The content cannot be filled with all width and height.

Others are similar to those in ①.

Differences in application scenarios

At the beginning, the article briefly summarized the application scenarios of Method ① and Method ②, and explained here:

1. From the basic usage, you can see the method ① It is a simple alternativeDialog Provides a very convenient way to create, with advantages over method ②
2. Method ① If multithreading (such as network request) is used, the current state of the Fragment cannot be correctly obtained, and a null pointer exception will be generated. Method ② does not have this problem, and the creation method uses a custom view by default, which is easier to deal with complex UI scenarios.

Here are examples: Method ① and Method ②//Do somethingAt the code, we perform some asynchronous operations:

TextView title = (.dialoag_tv);
("Value A");
new SomeTask().execute(url);
private class SomeTask extends AsyncTask<String, Void, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
      // Some network requests      // Return true when successful;      // Return false in exception;    }
    @Override
    protected void onPostExecute(Boolean aBoolean) {
      (aBoolean);
      // if (!isVisible()) return;
      if (aBoolean) {
        ("Value B");
      }
    }
}

If the current request is not finished or is closed when the network request is just finishedDialogFragment , line 19 of code will report a null pointer exception, and the function of code 17 is to judgeDialogFragment Is the current state available?isVisible()as well asisHide()For method ①, it cannot return its status correctly, method ② is normal. Method ① and Method ② CreateDialogFragment Some states are not exactly consistent.

PS: You can also use static Handler combined with weak references, etc. to handle asynchronous operations, which is not important for obtaining DialogFragment state.

Summarize

The above is a summary and opinion of my personal in the actual development process. I hope you can try it with a doubtful attitude. If you have new opinions or there are incorrect points in the article, please feel free to contact me.

For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.