Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/37815413
1. Overview Dialogfragment was introduced at Android 3.0.
is a special fragment that shows a modal dialog box on top of the activity's content.
Typical for: Show warning boxes. Input boxes, confirmation boxes, and so on.
Before Dialogfragment, we created a dialog box: Generally used Alertdialog and dialog. Note: It is not recommended to create a dialog directly using dialog.
2. Advantages and usage use Dialogfragment to manage dialog boxes. When you rotate the screen and press the back key to better manage its declaration cycle, it has a basically consistent declaration period with fragment.
And Dialogfragment also agreed with developers to reuse dialog as an embedded component, similar to fragment (able to show different effects on large screens and small screens). These advantages are shown in the examples above ~
The use of dialogfragment requires at least oncreateview or Oncreatedialog methods to be implemented.
Oncreateview uses the defined XML layout file to present the dialog. Oncreatedialog uses Alertdialog or dialog to create a dialog.
3. Rewrite Oncreateview Create dialog
A) layout file, we create a layout file that sets the name:
<?XML version= "1.0" encoding= "Utf-8"?
><relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Wrap_ Content "android:layout_height=" wrap_content "> <textview android:id=" @+id/id_label_your_name "a Ndroid:layout_width= "Wrap_content" android:layout_height= "32DP" android:gravity= "center_vertical" and roid:text= "Your name:"/> <edittext 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 "Androi d:imeoptions= "Actiondone" android:inputtype= "text"/> <button android:id= "@+id/id_sure_edit_name" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_alignparentrig Ht= "true" android:layout_below= "@id/id_txt_your_name" android:text= "OK"/></relativelayout>
b) inherit dialogfragment, override Oncreateview method
Package Com.example.zhy_dialogfragment;import Android.app.dialogfragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public Class Editnamedialogfragment extends dialogfragment{@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup Container,bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment_edit_name, container); return View;}}
c) Test Execution:
Called in the Main method:
public void Showeditdialog (view view) {editnamedialogfragment Editnamedialog = new Editnamedialogfragment (); Editnamedialog.show (Getfragmentmanager (), "Editnamedialog");}
:
Can see. The dialog box was successfully created and displayed, but the default dialog has a nasty title. How do we get rid of it: be able to call Getdialog () in Oncreateview. Requestwindowfeature (Window.feature_no_title); That
public class Editnamedialogfragment extends dialogfragment{@Overridepublic View oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {Getdialog (). Requestwindowfeature (Window.feature_no_title); View view = Inflater.inflate (R.layout.fragment_edit_name, container); return view;}}
:
It was perfect to get rid of the nasty headlines.
4, rewrite oncreatedialog Create dialog in Oncreatedialog generally can use Alertdialog or dialog Create dialog box, but since Google does not recommend the direct use of dialog, We'll use Alertdialog to create a login dialog box.
A) Layout file
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:orientation=" vertical " > <imageview android:layout_width= "match_parent" android:layout_height= "64DP" android:backgr Ound= "#FFFFBB33" android:contentdescription= "@string/app_name" android:scaletype= "center" android:src = "@drawable/title"/> <edittext android:id= "@+id/id_txt_username" android:layout_width= "Match_paren T "android:layout_height=" wrap_content "android:layout_marginbottom=" 4DP "android:layout_marginleft=" 4DP "android:layout_marginright=" 4DP "android:layout_margintop=" 16DP "android:hint=" input username " Android:inputtype= "textemailaddress"/> <edittext android:id= "@+id/id_txt_password" android:l Ayout_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" and roid:hint= "Input password" android:inputtype= "Textpassword"/></linearlayout>
b) Inherit Dialogfragment rewrite Oncreatedialog method
Package Com.example.zhy_dialogfragment;import Android.app.alertdialog;import Android.app.dialog;import Android.app.dialogfragment;import Android.content.dialoginterface;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.EditText ;p ublic class Logindialogfragment extends dialogfragment{@Overridepublic Dialog Oncreatedialog (Bundle Savedinstancestate) {Alertdialog.builder Builder = new Alertdialog.builder (getactivity ());//Get the layout Inflaterlayoutinflater inflater = getactivity (). Getlayoutinflater (); View view = Inflater.inflate (R.layout.fragment_login_dialog, NULL);//Inflate and set the layout for the dialog//Pass nul L as the parent view because its going in the dialog layoutbuilder.setview (view)//ADD action Buttons.setpositivebutton ("S IGN in ", New Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int id) {}}). Setnegativebutton ("Cancel", null); return builder.creatE ();}}
c) Call
public void Showlogindialog (view view) {logindialogfragment dialog = new Logindialogfragment ();d ialog.show ( Getfragmentmanager (), "Logindialog");}
:
Be able to see by overriding oncreatedialog the same ability to implement the Create dialog box. The effect is very nice.
5. Transfer data to activity
By passing data from dialog to activity, you can use the "Fragment interface pattern" approach, which is shown by a modified login box above.
The change is smaller. Directly post code:
Package Com.example.zhy_dialogfragment;import Android.app.alertdialog;import Android.app.dialog;import Android.app.dialogfragment;import Android.content.dialoginterface;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.EditText ;p ublic class Logindialogfragment extends Dialogfragment{private EditText musername;private EditText mpassword;public Interface logininputlistener{void Onlogininputcomplete (string Username, string password);} @Overridepublic Dialog Oncreatedialog (Bundle savedinstancestate) {Alertdialog.builder Builder = new Alertdialog.builder (Getactivity ());//Get the layout inflaterlayoutinflater inflater = getactivity (). Getlayoutinflater (); View view = 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);//Inflate and set the layout for the dialog Pass NULL as the PArent view because its going in the dialog layoutbuilder.setview (view)//ADD action Buttons.setpositivebutton ("Sign in", NE W Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int id) {Logininputlistener Listener = (Logininputlistener) getactivity (); Listener.onlogininputcomplete (Musername.gettext (). toString (), Mpassword.gettext (). toString ());}). Setnegativebutton ("Cancel", null); return builder.create ();}}
Get username and password references, when clicking Login, the activity is strong to our own defined interface: Logininputlistener. The data entered by the user is then returned.
We need to implement our interface Logininputlistener in mainactivity. To implement our approach. will be able to achieve when the user clicks the login, get our account password:
c) mainactivitypackage Com.example.zhy_dialogfragment;import com.example.zhy_dialogfragment. Logindialogfragment.logininputlistener;import Android.app.activity;import Android.app.alertdialog;import Android.content.dialoginterface;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.widget.toast;public class Mainactivity extends Activity implements logininputlistener{@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) ; Setcontentview (R.layout.activity_main);} public void Showlogindialog (view view) {logindialogfragment dialog = new Logindialogfragment ();d ialog.show ( Getfragmentmanager (), "Logindialog");} @Overridepublic void Onlogininputcomplete (string username, string password) {Toast.maketext (this, "account number:" + Username + ", c0/> Password: "+ Password,toast.length_short). Show ();}}
Effect:
6, dialogfragment do screen adaptation
We hope. A dialog box is displayed on the large screen as a dialog box. The small screen is directly embedded in the current actvity. This effect of the dialog box can only be achieved by rewriting Oncreateview. Below we use the above editnamedialogfragment to display.
Editnamedialogfragment we've written it. Write calls directly in the Mainactivity
public void Showdialogindifferentscreen (view view) {Fragmentmanager Fragmentmanager = Getfragmentmanager (); Editnamedialogfragment newfragment = new Editnamedialogfragment (); Boolean mislargelayout = Getresources (). GetBoolean ( R.bool.large_layout); LOG.E ("TAG", mislargelayout+ ""); if (mislargelayout) {//The device is using a large layout, so show the fragment as a//di Alognewfragment.show (Fragmentmanager, "dialog");} else{//the device is smaller, so show the fragment fullscreenfragmenttransaction transaction = Fragmentmanager.begintrans Action ();//For a little Polish, specify a transition animationtransaction.settransition (fragmenttransaction.transit_ Fragment_open);//To make it fullscreen with the ' content ' root view as the//container//for the FRAGMENT, which is alway s The root view for the Activitytransaction.replace (R.id.id_ly, newfragment). commit ();}}
Can see. We read through the r.bool.large_layout. The resulting Boolean value is then relied upon. Assuming that the large screen is displayed directly in the dialog box. Let's say a small screen is embedded in our activity layout.
This r.bool.large_layout is a resource file that we define:
Create a new bools.xml under the default values
<?XML version= "1.0" encoding= "Utf-8"?
><resources> <bool name= "Large_layout" >false</bool></resources>
Then create a new values-large under Res. Create a new bools.xml under the Values-large.
<?XML version= "1.0" encoding= "Utf-8"?
><resources> <bool name= "Large_layout" >true</bool></resources>
Last Test:
Emulator on the left and my phone on the right ~~~~~
7. Screen rotation
When the user enters the account password. Suddenly rotated the screen, account password disappeared ~ ~ ~ will be crazy
The traditional new alertdialog in the screen rotation, the first will not save the user input values, the second will report an exception, because the activity was destroyed before the dialog box is not closed. Dialogs implemented through Dialogfragment can be completely unnecessary to consider the problem of rotation.
We directly put the above login using the login box created by Alertdialog and copy it to mainactivity directly:
public void showlogindialogwithoutfragment (view view) {Alertdialog.builder Builder = new Alertdialog.builder (this);// Get the layout inflaterlayoutinflater inflater = This.getlayoutinflater ();//Inflate and set the layout for the dialog//P The because of the parent view is going in the dialog Layoutbuilder.setview (inflater.inflate (r.layout.fragment_login _dialog, NULL))//ADD action Buttons.setpositivebutton ("Sign in", New Dialoginterface.onclicklistener () {@ overridepublic void OnClick (dialoginterface dialog, int id) {//Sign in the user ...}}). Setnegativebutton ("Cancel", null). Show ();
Here are the two ways I can create a login box:
Can see, the traditional dialog rotate the screen disappears, and the background log will be reported abnormal ~ ~ ~ Use Dialogfragment is not affected.
All right. About Dialogfragment the end of the introduction ~ ~ ~
Have any questions please leave a message
Source code click to download
Documentation:
Http://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment
Https://github.com/thecodepath/android_guides/wiki/Using-DialogFragment
Android Official Recommendation: dialogfragment Create dialog box