Android Official Recommendation: dialogfragment Create dialog box

Source: Internet
Author: User

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 use: Display warning boxes, input boxes, confirmation boxes, and so on.
Before Dialogfragment, we created the dialog box: Alertdialog and dialog are generally used. Note: It is not recommended to create a dialog directly using dialog.
2. Benefits and usage using dialogfragment to manage dialogs, you can better manage their declaration cycles when rotating the screen and pressing the back key, which has a basically consistent declaration period with fragment. And Dialogfragment also allows developers to reuse dialog as an inline component, similar to fragment (which can show different effects on large screens and small screens). These benefits are shown in the examples above ~

At a minimum, you need to implement Oncreateview or Oncreatedialog methods with Dialogfragment. 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 androi D:id= "@+id/id_label_your_name" android:layout_width= "wrap_content" android:layout_height= "32DP" Andro Id:gravity= "center_vertical" android:text= "Your name:"/> <edittext android:id= "@+id/id_txt_your_na Me "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layout_torightof        = "@id/id_label_your_name" android:imeoptions= "Actiondone" android:inputtype= "text"/> <button Android:id= "@+id/id_sure_edit_name" android:layout_width= "wrap_content" android:layout_height= "Wrap_conten T "android:layout_alignparentright=" true "android:layout_below=" @id/id_txt_your_name "android:text=" O K "/></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 run:

Called in the Main method:

public void Showeditdialog (view view) {editnamedialogfragment Editnamedialog = new Editnamedialogfragment (); Editnamedialog.show (Getfragmentmanager (), "Editnamedialog");}

As you can see, the dialog box was created and displayed, but the default dialog has a nasty headline, how do we get rid of it: You can call Getdialog () in Oncreateview. Requestwindowfeature (Window.feature_no_ (TITLE), can be removed. 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 can generally 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");}


You can see that by overriding oncreatedialog the same can be done to create a dialog box, the effect is very nice.

5. Transfer data to activity

To transfer data from dialog to activity, you can use the "Fragment interface Pattern" method, which is shown below through a retrofit login box.

The changes are small, directly affixed to the 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 the username and password references, and when you click Log in, move the activity to our custom interface: Logininputlistener, and then return the data entered by the user.

Mainactivity need to implement our interface Logininputlistener, the implementation of our approach, we can achieve when the user click on the login, access to 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 want a dialog box to appear on the big screen as a dialog box, while the small screen is directly embedded in the current actvity. The dialog box for this effect can only be implemented by overriding Oncreateview. Below we use the above editnamedialogfragment to display.

Editnamedialogfragment we have written it, write the call 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 ();}}

As you can see, we read the r.bool.large_layout, and then according to the resulting Boolean value, if it is a large screen is displayed directly in the dialog box, if it is a small screen 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 and create a new bools.xml under Values-large.

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <bool name= "Large_layout" >true</bool ></resources>

Final Test:


Emulator on the left and my phone on the right ~~~~~

7. Screen rotation

When the user entered the account password, suddenly rotated the screen, the account password is missing ~ ~ ~ will be crazy

The traditional new alertdialog when the screen rotates, the first will not save the user input value, the second will report an exception, because the activity is destroyed before the dialog box is not allowed to close. The dialog that is 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 I click the two ways to create a login box, see:


As you can see, the traditional dialog rotating the screen disappears, and the background log will be reported abnormal ~ ~ ~ Use Dialogfragment is not affected.



All right, here's the end of the dialogfragment.


Have any questions please leave a message


SOURCE Click to download


Reference Documentation:

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

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

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.