Android official recommendation: How to Create a dialog box for DialogFragment

Source: Internet
Author: User

Android official recommendation: How to Create a dialog box for DialogFragment
1. Overview DialogFragment was introduced when android 3.0 was launched. Is a Special Fragment used to display a modal dialog box on the content of the Activity. It is typically used to display warning boxes, input boxes, confirmation boxes, and so on.
Before DialogFragment is generated, we create a Dialog box: Generally, AlertDialog and Dialog are used. Note: The Dialog create Dialog box is not officially recommended.
2. Benefits and usage use DialogFragment to manage the dialog box. When the revolving screen and press the back key, you can better manage its declaration cycle. It has a basically consistent declaration cycle with Fragment. DialogFragment also allows developers to reuse Dialog as embedded components, similar to Fragment (which can display different effects on large and small screens ). The preceding examples show these benefits ~

To use DialogFragment, you must at least implement the onCreateView or onCreateDIalog method. OnCreateView displays the Dialog using the defined xml layout file. OnCreateDialog: You can use AlertDialog or Dialog to create a Dialog.

3. Override onCreateView to create a Dialog

A) Layout file. We create a layout file with the name set:

 

[Html]View plaincopy
  1.  
  2. Android: layout_width = "wrap_content"
  3. Android: layout_height = "wrap_content">
  4.  
  5. Android: id = "@ + id/id_label_your_name"
  6. Android: layout_width = "wrap_content"
  7. Android: layout_height = "32dp"
  8. Android: gravity = "center_vertical"
  9. Android: text = "Yourname:"/>
  10.  
  11. Android: id = "@ + id/id_txt_your_name"
  12. Android: layout_width = "match_parent"
  13. Android: layout_height = "wrap_content"
  14. Android: layout_toRightOf = "@ id/id_label_your_name"
  15. Android: imeOptions = "actionDone"
  16. Android: inputType = "text"/>
  17.  
  18. Android: id = "@ + id/id_sure_edit_name"
  19. Android: layout_width = "wrap_content"
  20. Android: layout_height = "wrap_content"
  21. Android: layout_alignParentRight = "true"
  22. Android: layout_below = "@ id/id_txt_your_name"
  23. Android: text = "OK"/>
  24.  
  25.  
    B) inherit DialogFragment and override the onCreateView method.

     

     

    [Java]View plaincopy
    1. Packagecom. example. zhy_dialogfragment;
    2.  
    3. Importandroid. app. DialogFragment;
    4. Importandroid. OS. Bundle;
    5. Importandroid. view. LayoutInflater;
    6. Importandroid. view. View;
    7. Importandroid. view. ViewGroup;
    8.  
    9. PublicclassEditNameDialogFragmentextendsDialogFragment
    10. {
    11.  
    12.  
    13. @ Override
    14. PublicViewonCreateView (LayoutInflaterinflater, ViewGroupcontainer,
    15. BundlesavedInstanceState)
    16. {
    17. Viewview = inflater. inflate (R. layout. fragment_edit_name, container );
    18. Returnview;
    19. }
    20.  
    21. }
      C) test run:

       

      Call in the Main method:

       

      [Java]View plaincopy
      1. PublicvoidshowEditDialog (Viewview)
      2. {
      3. EditNameDialogFragmenteditNameDialog = newEditNameDialogFragment ();
      4. EditNameDialog. show (getFragmentManager (), "EditNameDialog ");
      5. }:

         

         

        As you can see, the dialog box is successfully created and displayed, but the default dialog box has a nasty title. How can we remove it: You can call getDialog () in onCreateView (). requestWindowFeature (Window. FEATURE_NO_TITLE); To remove it. That is:[Java]View plaincopy
        1. PublicclassEditNameDialogFragmentextendsDialogFragment
        2. {
        3.  
        4. @ Override
        5. PublicViewonCreateView (LayoutInflaterinflater, ViewGroupcontainer,
        6. BundlesavedInstanceState)
        7. {
        8. GetDialog (). requestWindowFeature (Window. FEATURE_NO_TITLE );
        9. Viewview = inflater. inflate (R. layout. fragment_edit_name, container );
        10. Returnview;
        11. }
        12.  
        13. }
          : It's perfect to get rid of nasty titles. 4. Override onCreateDialog to create a Dialog in onCreateDialog. Generally, you can use AlertDialog or Dialog to create a Dialog box. However, since google does not recommend using Dialog directly, AlertDialog is used to create a login Dialog box.

           

          A) Layout File

           

          [Html]View plaincopy
          1.  
          2. Android: layout_width = "wrap_content"
          3. Android: layout_height = "wrap_content"
          4. Android: orientation = "vertical">
          5.  
          6. Android: layout_width = "match_parent"
          7. Android: layout_height = "64dp"
          8. Android: background = "# FFFFBB33"
          9. Android: contentDescription = "@ string/app_name"
          10. Android: scaleType = "center"
          11. Android: src = "@ drawable/title"/>
          12.  
          13. Android: id = "@ + id/id_txt_username"
          14. Android: layout_width = "match_parent"
          15. Android: layout_height = "wrap_content"
          16. Android: layout_marginBottom = "4dp"
          17. Android: layout_marginLeft = "4dp"
          18. Android: layout_marginRight = "4dp"
          19. Android: layout_marginTop = "16dp"
          20. Android: hint = "inputusername"
          21. Android: inputType = "textEmailAddress"/>
          22.  
          23. Android: id = "@ + id/id_txt_password"
          24. Android: layout_width = "match_parent"
          25. Android: layout_height = "wrap_content"
          26. Android: layout_marginBottom = "16dp"
          27. Android: layout_marginLeft = "4dp"
          28. Android: layout_marginRight = "4dp"
          29. Android: layout_marginTop = "4dp"
          30. Android: fontFamily = "sans-serif"
          31. Android: hint = "inputpassword"
          32. Android: inputType = "textPassword"/>
          33.  
          34.  
            B) inherit the DialogFragment and override the onCreateDialog method.

             

             

            [Java]View plaincopy
            1. Packagecom. example. zhy_dialogfragment;
            2.  
            3. Importandroid. app. AlertDialog;
            4. Importandroid. app. Dialog;
            5. Importandroid. app. DialogFragment;
            6. Importandroid. content. DialogInterface;
            7. Importandroid. OS. Bundle;
            8. Importandroid. view. LayoutInflater;
            9. Importandroid. view. View;
            10. Importandroid. view. ViewGroup;
            11. Importandroid. widget. EditText;
            12.  
            13. PublicclassLoginDialogFragmentextendsDialogFragment
            14. {
            15.  
            16. @ Override
            17. PublicDialogonCreateDialog (BundlesavedInstanceState)
            18. {
            19. AlertDialog. Builderbuilder = newAlertDialog. Builder (getActivity ());
            20. // Getthelayoutinflater
            21. LayoutInflaterinflater = getActivity (). getLayoutInflater ();
            22. Viewview = inflater. inflate (R. layout. fragment_login_dialog, null );
            23. // Inflateandsetthelayoutforthedialog
            24. // Passnullastheparentviewbecauseitsgoinginthedialoglayout
            25. Builder. setView (view)
            26. // Addactionbuttons
            27. . SetPositiveButton ("Signin ",
            28. NewDialogInterface. OnClickListener ()
            29. {
            30. @ Override
            31. PublicvoidonClick (DialogInterfacedialog, intid)
            32. {
            33. }
            34. }). SetNegativeButton ("Cancel", null );
            35. Returnbuilder. create ();
            36. }
            37. }
              C) Call

               

               

              [Java]View plaincopy
              1. PublicvoidshowLoginDialog (Viewview)
              2. {
              3. LoginDialogFragmentdialog = newLoginDialogFragment ();
              4. Dialog. show (getFragmentManager (), "loginDialog ");
              5. }
                :

                 

                 

                You can see that by rewriting onCreateDialog, you can also create a dialog box, which is nice.

                5. pass data to Activity

                When data is transmitted from the dialog to the Activity, you can use the "fragment interface pattern" method. The following shows the mode by modifying the logon box above.

                The changes are relatively small and the code is directly pasted:

                 

                [Java]View plaincopy
                1. Packagecom. example. zhy_dialogfragment;
                2.  
                3. Importandroid. app. AlertDialog;
                4. Importandroid. app. Dialog;
                5. Importandroid. app. DialogFragment;
                6. Importandroid. content. DialogInterface;
                7. Importandroid. OS. Bundle;
                8. Importandroid. view. LayoutInflater;
                9. Importandroid. view. View;
                10. Importandroid. view. ViewGroup;
                11. Importandroid. widget. EditText;
                12.  
                13. PublicclassLoginDialogFragmentextendsDialogFragment
                14. {
                15. PrivateEditTextmUsername;
                16. PrivateEditTextmPassword;
                17.  
                18. PublicinterfaceLoginInputListener
                19. {
                20. VoidonLoginInputComplete (Stringusername, Stringpassword );
                21. }
                22.  
                23. @ Override
                24. PublicDialogonCreateDialog (BundlesavedInstanceState)
                25. {
                26. AlertDialog. Builderbuilder = newAlertDialog. Builder (getActivity ());
                27. // Getthelayoutinflater
                28. LayoutInflaterinflater = getActivity (). getLayoutInflater ();
                29. Viewview = inflater. inflate (R. layout. fragment_login_dialog, null );
                30. MUsername = (EditText) view. findViewById (R. id. id_txt_username );
                31. MPassword = (EditText) view. findViewById (R. id. id_txt_password );
                32. // Inflateandsetthelayoutforthedialog
                33. // Passnullastheparentviewbecauseitsgoinginthedialoglayout
                34. Builder. setView (view)
                35. // Addactionbuttons
                36. . SetPositiveButton ("Signin ",
                37. NewDialogInterface. OnClickListener ()
                38. {
                39. @ Override
                40. PublicvoidonClick (DialogInterfacedialog, intid)
                41. {
                42. LoginInputListenerlistener = (LoginInputListener) getActivity ();
                43. Listener. onLoginInputComplete (mUsername
                44. . GetText (). toString (), mPassword
                45. . GetText (). toString ());
                46. }
                47. }). SetNegativeButton ("Cancel", null );
                48. Returnbuilder. create ();
                49. }
                50. }
                  Get the reference of username and password. When you click Login, convert activity into our custom interface: LoginInputListener, and then return the user input data.

                   

                  In MainActivity, we need to implement our interface loginputlistener to implement our method, so that we can obtain our account password when users click Login:

                   

                  [Java]View plaincopy
                  1. C) MainActivity
                  2. Packagecom. example. zhy_dialogfragment;
                  3.  
                  4. Importcom. example. zhy_dialogfragment.LoginDialogFragment.LoginInputListener;
                  5.  
                  6. Importandroid. app. Activity;
                  7. Importandroid. app. AlertDialog;
                  8. Importandroid. content. DialogInterface;
                  9. Importandroid. OS. Bundle;
                  10. Importandroid. view. LayoutInflater;
                  11. Importandroid. view. View;
                  12. Importandroid. widget. Toast;
                  13.  
                  14. PublicclassMainActivityextendsActivityimplementsLoginInputListener
                  15. {
                  16.  
                  17. @ Override
                  18. ProtectedvoidonCreate (BundlesavedInstanceState)
                  19. {
                  20. Super. onCreate (savedInstanceState );
                  21. SetContentView (R. layout. activity_main );
                  22. }
                  23.  
                  24.  
                  25.  
                  26. PublicvoidshowLoginDialog (Viewview)
                  27. {
                  28. LoginDialogFragmentdialog = newLoginDialogFragment ();
                  29. Dialog. show (getFragmentManager (), "loginDialog ");
                  30.  
                  31. }
                  32.  
                  33. @ Override
                  34. PublicvoidonLoginInputComplete (Stringusername, Stringpassword)
                  35. {
                  36. Toast. makeText (this, "account:" + username + ", password:" + password,
                  37. Toast. LENGTH_SHORT). show ();
                  38. }
                  39.  
                  40. }
                    Effect:

                     

                    6. DialogFragment for Screen Adaptation

                    We hope that a dialog box will be displayed in the form of a dialog box on the large screen, while a small screen will be directly embedded in the current Actvity. The dialog box with this effect can only be implemented by rewriting onCreateView. The above EditNameDialogFragment is used for display.

                    EditNameDialogFragment we have already compiled it and directly write the call in MainActivity

                     

                    [Java]View plaincopy
                    1. PublicvoidshowDialogInDifferentScreen (Viewview)
                    2. {
                    3. FragmentManagerfragmentManager = getFragmentManager ();
                    4. EditNameDialogFragmentnewFragment = newEditNameDialogFragment ();
                    5.  
                    6. BooleanmIsLargeLayout = getResources (). getBoolean (R. bool. large_layout );
                    7. Log. e ("TAG", mIsLargeLayout + "");
                    8. If (mIsLargeLayout)
                    9. {
                    10. // Thedeviceisusingalargelayout, soshowthefragmentasa
                    11. // Dialog
                    12. NewFragment. show (fragmentManager, "dialog ");
                    13. } Else
                    14. {
                    15. // Thedeviceissmaller, soshowthefragmentfullscreen
                    16. FragmentTransactiontransaction = fragmentManager
                    17. . BeginTransaction ();
                    18. // Foralittlepolish, specifyatransitionanimation
                    19. Transaction
                    20. . SetTransition (FragmentTransaction. TRANSIT_FRAGMENT_OPEN );
                    21. // Tomakeitfullscreen, usethe 'content' rootviewasthe
                    22. // Container
                    23. // Forthefragment, whichisalwaystherootviewfortheactivity
                    24. Transaction. replace (R. id. id_ly, newFragment)
                    25. . Commit ();
                    26. }
                    27. }
                      We can see that by reading R. bool. large_layout, and then based on the obtained Boolean value, if it is a large screen, it will be displayed in a dialog box. If it is a small screen, it will be embedded in our Activity layout.

                       

                      This R. bool. large_layout is the resource file we have defined:

                      Create a bools. xml file under the default values

                       

                      [Html]View plaincopy
                      1.  
                      2.  
                      3. False
                      4.  
                      5.  
                      6.  
                        Create a values-large file under res and create a bools. xml file under values-large.

                         

                         

                        [Html]View plaincopy
                        1.  
                        2.  
                        3. True
                        4.  
                        5.  
                        6.  
                          Last test:

                           

                          Simulator on the left and mobile phone on the right ~~~~~

                          7. Screen Rotation

                          When the user enters the account password, the screen is suddenly rotated, And the account password is missing ~~~ Is it crazy?

                          When the traditional new AlertDialog is rotated on the screen, the user input value is not saved first, and an exception is reported because the dialog box cannot be closed before the Activity is destroyed. The dialog box implemented through DialogFragment does not need to be rotated at all.

                          We directly copy the logon box created by using AlertDialog and copy it to MainActivity to directly call:

                           

                          [Java]View plaincopy
                          1. PublicvoidshowLoginDialogWithoutFragment (Viewview)
                          2. {
                          3. AlertDialog. Builderbuilder = newAlertDialog. Builder (this );
                          4. // Getthelayoutinflater
                          5. LayoutInflaterinflater = this. getLayoutInflater ();
                          6.  
                          7. // Inflateandsetthelayoutforthedialog
                          8. // Passnullastheparentviewbecauseitsgoinginthedialoglayout
                          9. Builder. setView (inflater. inflate (R. layout. fragment_login_dialog, null ))
                          10. // Addactionbuttons
                          11. . SetPositiveButton ("Signin ",
                          12. NewDialogInterface. OnClickListener ()
                          13. {
                          14. @ Override
                          15. PublicvoidonClick (DialogInterfacedialog, intid)
                          16. {
                          17. // Signintheuser...
                          18. }
                          19. }). SetNegativeButton ("Cancel", null). show ();
                          20. }
                            Next, I will click the login box created in two ways to see:

                             

                            As you can see, the traditional Dialog screen disappears when it is rotated, and the background log reports an exception ~~~ DialogFragment is not affected.

                             

                             

                            Now, the introduction to DialogFragment is complete ~~~~

                             

                            Leave a message if you have any questions.

                             

                            Download source code

                             

                            Reference:

                            Http://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment

                            Https://github.com/thecodepath/android_guides/wiki/Using-DialogFragment

                             

          Related Article

          Contact Us

          The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

          If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

          A Free Trial That Lets You Build Big!

          Start building with 50+ products and up to 12 months usage for Elastic Compute Service

          • Sales Support

            1 on 1 presale consultation

          • After-Sales Support

            24/7 Technical Support 6 Free Tickets per Quarter Faster Response

          • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.