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
-
- Android: layout_width = "wrap_content"
- Android: layout_height = "wrap_content">
-
- Android: id = "@ + id/id_label_your_name"
- Android: layout_width = "wrap_content"
- Android: layout_height = "32dp"
- Android: gravity = "center_vertical"
- Android: text = "Yourname:"/>
-
- Android: id = "@ + id/id_txt_your_name"
- Android: layout_width = "match_parent"
- Android: layout_height = "wrap_content"
- Android: layout_toRightOf = "@ id/id_label_your_name"
- Android: imeOptions = "actionDone"
- Android: inputType = "text"/>
-
- Android: id = "@ + id/id_sure_edit_name"
- Android: layout_width = "wrap_content"
- Android: layout_height = "wrap_content"
- Android: layout_alignParentRight = "true"
- Android: layout_below = "@ id/id_txt_your_name"
- Android: text = "OK"/>
-
-
B) inherit DialogFragment and override the onCreateView method.
[Java]View plaincopy
- Packagecom. example. zhy_dialogfragment;
-
- Importandroid. app. DialogFragment;
- Importandroid. OS. Bundle;
- Importandroid. view. LayoutInflater;
- Importandroid. view. View;
- Importandroid. view. ViewGroup;
-
- PublicclassEditNameDialogFragmentextendsDialogFragment
- {
-
-
- @ Override
- PublicViewonCreateView (LayoutInflaterinflater, ViewGroupcontainer,
- BundlesavedInstanceState)
- {
- Viewview = inflater. inflate (R. layout. fragment_edit_name, container );
- Returnview;
- }
-
- }
C) test run:
Call in the Main method:
[Java]View plaincopy
- PublicvoidshowEditDialog (Viewview)
- {
- EditNameDialogFragmenteditNameDialog = newEditNameDialogFragment ();
- EditNameDialog. show (getFragmentManager (), "EditNameDialog ");
- }:
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
- PublicclassEditNameDialogFragmentextendsDialogFragment
- {
-
- @ Override
- PublicViewonCreateView (LayoutInflaterinflater, ViewGroupcontainer,
- BundlesavedInstanceState)
- {
- GetDialog (). requestWindowFeature (Window. FEATURE_NO_TITLE );
- Viewview = inflater. inflate (R. layout. fragment_edit_name, container );
- Returnview;
- }
-
- }
: 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
-
- Android: layout_width = "wrap_content"
- Android: layout_height = "wrap_content"
- Android: orientation = "vertical">
-
- Android: layout_width = "match_parent"
- Android: layout_height = "64dp"
- Android: background = "# FFFFBB33"
- Android: contentDescription = "@ string/app_name"
- Android: scaleType = "center"
- Android: src = "@ drawable/title"/>
-
- Android: id = "@ + id/id_txt_username"
- Android: layout_width = "match_parent"
- Android: layout_height = "wrap_content"
- Android: layout_marginBottom = "4dp"
- Android: layout_marginLeft = "4dp"
- Android: layout_marginRight = "4dp"
- Android: layout_marginTop = "16dp"
- Android: hint = "inputusername"
- Android: inputType = "textEmailAddress"/>
-
- Android: id = "@ + id/id_txt_password"
- Android: layout_width = "match_parent"
- Android: layout_height = "wrap_content"
- Android: layout_marginBottom = "16dp"
- Android: layout_marginLeft = "4dp"
- Android: layout_marginRight = "4dp"
- Android: layout_marginTop = "4dp"
- Android: fontFamily = "sans-serif"
- Android: hint = "inputpassword"
- Android: inputType = "textPassword"/>
-
-
B) inherit the DialogFragment and override the onCreateDialog method.
[Java]View plaincopy
- Packagecom. example. zhy_dialogfragment;
-
- Importandroid. app. AlertDialog;
- Importandroid. app. Dialog;
- Importandroid. app. DialogFragment;
- Importandroid. content. DialogInterface;
- Importandroid. OS. Bundle;
- Importandroid. view. LayoutInflater;
- Importandroid. view. View;
- Importandroid. view. ViewGroup;
- Importandroid. widget. EditText;
-
- PublicclassLoginDialogFragmentextendsDialogFragment
- {
-
- @ Override
- PublicDialogonCreateDialog (BundlesavedInstanceState)
- {
- AlertDialog. Builderbuilder = newAlertDialog. Builder (getActivity ());
- // Getthelayoutinflater
- LayoutInflaterinflater = getActivity (). getLayoutInflater ();
- Viewview = inflater. inflate (R. layout. fragment_login_dialog, null );
- // Inflateandsetthelayoutforthedialog
- // Passnullastheparentviewbecauseitsgoinginthedialoglayout
- Builder. setView (view)
- // Addactionbuttons
- . SetPositiveButton ("Signin ",
- NewDialogInterface. OnClickListener ()
- {
- @ Override
- PublicvoidonClick (DialogInterfacedialog, intid)
- {
- }
- }). SetNegativeButton ("Cancel", null );
- Returnbuilder. create ();
- }
- }
C) Call
[Java]View plaincopy
- PublicvoidshowLoginDialog (Viewview)
- {
- LoginDialogFragmentdialog = newLoginDialogFragment ();
- Dialog. show (getFragmentManager (), "loginDialog ");
- }
:
You can see that by rewriting onCreateDialog, you can also create a dialog box, which is nice.
5. pass data to ActivityWhen 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
- Packagecom. example. zhy_dialogfragment;
-
- Importandroid. app. AlertDialog;
- Importandroid. app. Dialog;
- Importandroid. app. DialogFragment;
- Importandroid. content. DialogInterface;
- Importandroid. OS. Bundle;
- Importandroid. view. LayoutInflater;
- Importandroid. view. View;
- Importandroid. view. ViewGroup;
- Importandroid. widget. EditText;
-
- PublicclassLoginDialogFragmentextendsDialogFragment
- {
- PrivateEditTextmUsername;
- PrivateEditTextmPassword;
-
- PublicinterfaceLoginInputListener
- {
- VoidonLoginInputComplete (Stringusername, Stringpassword );
- }
-
- @ Override
- PublicDialogonCreateDialog (BundlesavedInstanceState)
- {
- AlertDialog. Builderbuilder = newAlertDialog. Builder (getActivity ());
- // Getthelayoutinflater
- LayoutInflaterinflater = getActivity (). getLayoutInflater ();
- Viewview = inflater. inflate (R. layout. fragment_login_dialog, null );
- MUsername = (EditText) view. findViewById (R. id. id_txt_username );
- MPassword = (EditText) view. findViewById (R. id. id_txt_password );
- // Inflateandsetthelayoutforthedialog
- // Passnullastheparentviewbecauseitsgoinginthedialoglayout
- Builder. setView (view)
- // Addactionbuttons
- . SetPositiveButton ("Signin ",
- NewDialogInterface. OnClickListener ()
- {
- @ Override
- PublicvoidonClick (DialogInterfacedialog, intid)
- {
- LoginInputListenerlistener = (LoginInputListener) getActivity ();
- Listener. onLoginInputComplete (mUsername
- . GetText (). toString (), mPassword
- . GetText (). toString ());
- }
- }). SetNegativeButton ("Cancel", null );
- Returnbuilder. create ();
- }
- }
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
- C) MainActivity
- Packagecom. example. zhy_dialogfragment;
-
- Importcom. example. zhy_dialogfragment.LoginDialogFragment.LoginInputListener;
-
- Importandroid. app. Activity;
- Importandroid. app. AlertDialog;
- Importandroid. content. DialogInterface;
- Importandroid. OS. Bundle;
- Importandroid. view. LayoutInflater;
- Importandroid. view. View;
- Importandroid. widget. Toast;
-
- PublicclassMainActivityextendsActivityimplementsLoginInputListener
- {
-
- @ Override
- ProtectedvoidonCreate (BundlesavedInstanceState)
- {
- Super. onCreate (savedInstanceState );
- SetContentView (R. layout. activity_main );
- }
-
-
-
- PublicvoidshowLoginDialog (Viewview)
- {
- LoginDialogFragmentdialog = newLoginDialogFragment ();
- Dialog. show (getFragmentManager (), "loginDialog ");
-
- }
-
- @ Override
- PublicvoidonLoginInputComplete (Stringusername, Stringpassword)
- {
- Toast. makeText (this, "account:" + username + ", password:" + password,
- Toast. LENGTH_SHORT). show ();
- }
-
- }
Effect:
6. DialogFragment for Screen AdaptationWe 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
- PublicvoidshowDialogInDifferentScreen (Viewview)
- {
- FragmentManagerfragmentManager = getFragmentManager ();
- EditNameDialogFragmentnewFragment = newEditNameDialogFragment ();
-
- BooleanmIsLargeLayout = getResources (). getBoolean (R. bool. large_layout );
- Log. e ("TAG", mIsLargeLayout + "");
- If (mIsLargeLayout)
- {
- // Thedeviceisusingalargelayout, soshowthefragmentasa
- // Dialog
- NewFragment. show (fragmentManager, "dialog ");
- } Else
- {
- // Thedeviceissmaller, soshowthefragmentfullscreen
- FragmentTransactiontransaction = fragmentManager
- . BeginTransaction ();
- // Foralittlepolish, specifyatransitionanimation
- Transaction
- . SetTransition (FragmentTransaction. TRANSIT_FRAGMENT_OPEN );
- // Tomakeitfullscreen, usethe 'content' rootviewasthe
- // Container
- // Forthefragment, whichisalwaystherootviewfortheactivity
- Transaction. replace (R. id. id_ly, newFragment)
- . Commit ();
- }
- }
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
-
-
-
- False
-
-
Create a values-large file under res and create a bools. xml file under values-large.
[Html]View plaincopy
-
-
-
- True
-
-
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
- PublicvoidshowLoginDialogWithoutFragment (Viewview)
- {
- AlertDialog. Builderbuilder = newAlertDialog. Builder (this );
- // Getthelayoutinflater
- LayoutInflaterinflater = this. getLayoutInflater ();
-
- // Inflateandsetthelayoutforthedialog
- // Passnullastheparentviewbecauseitsgoinginthedialoglayout
- Builder. setView (inflater. inflate (R. layout. fragment_login_dialog, null ))
- // Addactionbuttons
- . SetPositiveButton ("Signin ",
- NewDialogInterface. OnClickListener ()
- {
- @ Override
- PublicvoidonClick (DialogInterfacedialog, intid)
- {
- // Signintheuser...
- }
- }). SetNegativeButton ("Cancel", null). show ();
- }
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