Search code examples
androidperformancedialogcustomdialog

Custom dialog takes time to show up


When I implement a custom dialog by using AlertDialog.Builder or DialogFragment which has a fairly complex layout (like this one) the dialog takes time to show up. But when the dialog just contains a couple of editText or so... there is no issue in showing up of the dialog. Why is it so?

Is it that the AlertDialog framework is used to build dialogs that are used just to alert the users? (as the name implies.)

Are there some other frameworks that can be used to implement complex custom dialogs?

I have tried the following things to fix the issue:

  1. Attempted to implement threading so that my dialog is ready in a background thread and show it when I want. But this is not allowed in general as any other thread except UI thread aren't supposed to touch UI related events.
  2. Made the dialog a global variable, initialized it in onCreate and then show the dialog onButtonClick.
  3. Switched to CONSTRAINT LAYOUT
  4. Used an activity as a dialog by setting the dialog theme to the activity in the manifest file.

I am extending to this question. Any help would be highly appreciated, thanks in advance.


Solution

  • AlertDialog and DialogFragment frameworks are slow because they need to some time to do calculations and fragment stuffs. So a solution to this problem is, using the Dialog framework straight away.

    1. Use the Dialog framework's constructor to initialize a Dialog object like this:

      Dialog dialog = new Dialog(context, R.style.Theme_AppCompat_Dialog);
      // the second parameter is not compulsory and you can use other themes as well
      
    2. Define the layout and then use dialog.setContentView(R.layout.name_of_layout).

    3. Use dialog.findViewById(R.id.name_of_view) to reference views from the dialog's layout file

    And then implement the logic just like anyone would do in an activity class. Find out the best implementation for your use case by reading the official documentation.