Objective
Specific code and examples I put on Github, the need for friends can go to see Dialogfragmentdemos, welcome star and Fork.
The main content of this article
- What is Dialogfragment?
- Create a generic Commondialogfragment
- Implement various types of dialogfragment
Before writing the text, let's start with a wave of effects.
First, what is Dialogfragment?
Dialogfragment was introduced at Android 3.0 and is a special Fragment for displaying a static dialog box on top of the Activity's content. Examples: Warning boxes, input boxes, confirmation boxes, and so on.
1, the advantages of dialogfragment
In fact, there are two types of dialog boxes available in Android, one is dialogfragment and the other is Dialog. Before Dialogfragment generation, we create dialog box generally use Dialog, and from the code writing point of view, Dialog is actually more simple to use, but Google is recommended to use dialogfragment as far as possible, is not feeling very strange, In fact, the reason is also very simple, dialogfragment has the very good characteristic which Dialog does not have
- Dialogfragment itself is a subclass of Fragment, with the same life cycle as Fragment, using Dialogfragment to manage dialog boxes, and to better manage their lifecycles when rotating the screen and pressing the back button
- When changes in the phone configuration cause the Activity to be recreated, such as rotating the screen, the Dialogfragment-based dialog box will be automatically rebuilt by Fragmentmanager, but the Dialog-based dialog does not have the ability
2, the use of dialogfragment
Using dialogfragment requires at least the implementation of the Oncreateview () or Oncreatedialog () method, and Oncreateview () shows Dialog even with a custom XML layout file Oncreatedialog () that is, using Alertdialog or Dialog to create the Dialog we want, because this article is mainly about dialogfragment packaging, as for dialogfragment specific use, you can refer to the following the foreign God this article Android Officer Party recommendation: dialogfragment Create dialog box
Second, create a general commondialogfragment
This class is a subclass of Dialogfragment, encapsulates dialogfragment, relies on externally passed-in alertdialog to build, and also handles the problem that Alertdialog cannot set external cancellation in Dialogfragment
public class Commondialogfragment extends Dialogfragment {/** * listener popup is canceled */private Ondialogcancellistene R Mcancellistener; /** * Callback to get Dialog */private Oncalldialog Moncalldialog needed to be displayed; public interface Ondialogcancellistener {void OnCancel (); } public interface Oncalldialog {Dialog Getdialog (context context); } public static Commondialogfragment newinstance (Oncalldialog call, Boolean cancelable) {return newinstance (cal L, cancelable, NULL); } public static Commondialogfragment newinstance (Oncalldialog call, Boolean cancelable, Ondialogcancellistener cancelLi Stener) {Commondialogfragment instance = new Commondialogfragment (); Instance.setcancelable (cancelable); Instance.mcancellistener = Cancellistener; Instance.moncalldialog = call; return instance; } @Override Public Dialog oncreatedialog (Bundle savedinstancestate) {if (null = = Moncalldialog) { SupEr.oncreatedialog (savedinstancestate); } return Moncalldialog.getdialog (Getactivity ()); } @Override public void OnStart () {Super.onstart (); Dialog Dialog = Getdialog (); if (dialog! = NULL) {//A white background border appears in versions below 5.0, and if the setting above 5.0 causes the background of the text part to become transparent if (Build.VERSION.SDK_INT <= Build.version_codes. KITKAT) {//Currently only these two dialog will appear border if (Dialog instanceof ProgressDialog | | Dialog instanceof Date Pickerdialog) {Getdialog (). GetWindow (). setbackgrounddrawable (New colordrawable (color.transparent)); }} window window = Getdialog (). GetWindow (); Windowmanager.layoutparams windowparams = Window.getattributes (); Windowparams.dimamount = 0.0f; Window.setattributes (Windowparams); }} @Override public void OnCancel (Dialoginterface dialog) {super.oncancel (dialog); if (Mcancellistener! = null) { Mcancellistener.oncancel (); } }}
You can see that the code of this class is also very small, the first definition of two interface Ondialogcancellistener,oncalldialog, the former is used to listen to the popup is canceled, the latter can let us callback to get the Dialog to display, you can see the What we return in Oncreatedialog () is mOnCallDialog.getDialog(getActivity);
that when we pass in the Dialog, we will call back here and let Oncreatedialog () return to our incoming Dialog, and for 接口回调
a friend who is not very clear, you can read this article A classic example that gives you a thorough understanding of the Java callback mechanism
Then in OnStart () some special processing, because in the version below 5.0, ProgressDialog and Datepickerdialog will appear white border, which makes the user experience is very bad, so we have to do the appropriate processing here
The last is to encapsulate our constructors
newInstance(OnCallDialog call, boolean cancelable, OnDialogCancelListener cancelListener)
, when we want to use this commondialogfragment, first new a oncalldialog, the Dialog we want to display in, to cancelable
set whether the dialog can be canceled, you can see in the OnCancel () There is a code like this
if(mCancelListener != null){ mCancelListener.onCancel();}
This is why we passed Oncancellistener in the constructor, and when we want to do some cancellation of the dialog box, just pass in the Oncancellistener in the constructor, implement the OnCancel () method.
Three, the realization of various types of dialogfragment
Now that we've created Commonfragment as the base class for all dialogfragment, then of course we're going to have to implement all kinds of dialogfragment, and my idea is to create a Dialogfragmenthelper as a help class to implement the prompt, help us to encapsulate the code, use only to focus on the interaction with Alertdialog, helper will help us to use the dialogfragment to display, This will unify the entire application's Dialog style, but also allows us to implement a variety of dialog boxes become quite simple
We have two things to do before we implement Dialogfragmenthelper.
1. Define the style in the styles file we define our dialog box
<style name= "Base_alertdialog" parent= "Base.Theme.AppCompat.Light.Dialog" > <!--not set above 6.0 will appear, the width is not full screen of the situation-- > <item name= "Windowminwidthminor" >90%</item> <!--to cancel the title bar if Settitle in the code is invalid-- <item name= "Android:windownotitle" >true</item> < text color of!--title and message-<!--<item Name= "Android:textcolorprimary" > @color/black</item>--> <!--Modify the background color of the top title, the specific color itself, can be pictures--& Lt;item name= "Android:topdark" > @color/app_main_color_deep</item> <!--<item name= "Android: Background "> @color/white</item>--> <!--There are strange backgrounds after setting the background color on some systems, where the background is set to transparent, in order to hide the border--and <! --<item name= "Android:windowbackground" > @android:color/transparent</item>--> <!--<item name= "Android:windowframe" > @null </item>--> <!--Enter and exit animations, left-in-right (system comes with)-<!--<item Name= "an Droid:windowanimationstyle "> @android:style/animation.translucent</item>--> <!--button font color, all together, a single change needs to be modified in Java code--<item name= "C Oloraccent "> @color/app_main_color</item> </style>
I have already made a detailed comment and I believe it should be easy to understand.
2. Write an interface for data monitoring between the dialogfragmenthelper and the logic layer
public interface IDialogResultListener<T> { void onDataResult(T result);}
Preparation work done, let us start the dialogfragmenthelper, because space is limited, I just representative selected some of the results, the specific code, you can refer to the next Dialogfragmentdemos
public class Dialogfragmenthelper {private static final String Tag_head = DialogFragmentHelper.class.getSimpleName (); /** * Popup window in load * * private static final int progress_theme = R.style.base_alertdialog; private static final String Progress_tag = tag_head + ":p rogress"; public static commondialogfragment showprogress (Fragmentmanager fragmentmanager, String message) {return Showprogre SS (Fragmentmanager, message, true, NULL); public static commondialogfragment showprogress (Fragmentmanager fragmentmanager, String message, Boolean cancelable) { Return showprogress (fragmentmanager, message, cancelable, NULL); public static commondialogfragment showprogress (Fragmentmanager fragmentmanager, Final String message, Boolean cancel Able, Commondialogfragment.ondialogcancellistener Cancellistener) {commondialogfragment dialogFragment = Commondialogfragment.newinstance (New Commondialogfragment.oncalldialog () {@Override Public Dialog Getdialog (context context) {ProgressDialog ProgressDialog = new ProgressDialog (c Ontext, Progress_theme); Progressdialog.setmessage (message); return progressdialog; }}, cancelable, Cancellistener); Dialogfragment.show (Fragmentmanager, Progress_tag); return dialogfragment; }/** * pop-up window with input box */private static final int insert_theme = R.style.base_alertdialog; private static final String Insert_tag = Tag_head + ": INSERT"; public static void Showinsertdialog (Fragmentmanager Manager, final String title, final idialogresultlistener<string& Gt Resultlistener, Final Boolean cancelable) {commondialogfragment dialogfragment = commondialogfragment.newinstance (n EW Commondialogfragment.oncalldialog () {@Override public Dialog Getdialog (context context) { // ... Alertdialog.builder Builder = new Alertdialog.buildeR (context, insert_theme); Builder.setpositivebutton (dialog_positive, New Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {if (Resultlistener! = null) { Resultlistener.ondataresult (Edittext.gettext (). toString ()); } } }); Builder.setnegativebutton (dialog_negative, NULL); return Builder.create (); }}, cancelable, null); Dialogfragment.show (manager, Insert_tag); }}
It can be seen that the implementation of all these effects has become quite simple because we have encapsulated the commonfragment, which is the convenience and benefits of encapsulation.
Let's take the 加载中的弹出窗
example and see how we do it.
public static CommonDialogFragment showProgress(FragmentManager fragmentManager, final String message, boolean cancelable , CommonDialogFragment.OnDialogCancelListener cancelListener){ CommonDialogFragment dialogFragment = CommonDialogFragment.newInstance(new CommonDialogFragment.OnCallDialog() { @Override public Dialog getDialog(Context context) { ProgressDialog progressDialog = new ProgressDialog(context, PROGRESS_THEME); progressDialog.setMessage(message); return progressDialog; } }, cancelable, cancelListener); dialogFragment.show(fragmentManager, PROGRESS_TAG); return dialogFragment; }
We first call the Commondialogfragment constructor, pass a progressdialog in, then pass in Cancelable and Cancellistener, and finally call the show () function. Show the dialogfragment, because we use the overload of the constructor, you can see the simplest constructor only need to pass in two parameters on the line, is not quite concise ah.
We've created a IDialogResultListener<T>
data listener for dialogfragment and logic layers, so that I can pass in a variety of types of data, and I'm going to use it 泛型
as an example to 带输入框的弹出窗
see how to use it.
public static void Showinsertdialog (Fragmentmanager Manager, final String title, final idialogresultlistener<string > Resultlistener, Final boolean cancelable) {commondialogfragment dialogfragment = Commondialogfragment.newinsta NCE (New Commondialogfragment.oncalldialog () {@Override public Dialog Getdialog (context context) { // ... Part of the code is omitted here Alertdialog.builder Builder = new Alertdialog.builder (context, insert_theme); Builder.setpositivebutton (dialog_positive, New Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {if (Resultlistener! = null) { Resultlistener.ondataresult (Edittext.gettext (). toString ()); } } }); Builder.setnegativebutton (dialog_negative, NULL); return Builder.create (); }}, cancelable, null); Dialogfragment.show (manager, Insert_tag); }
You can see that we passed in the showInsertDialog()
method IDialogResultListener<String> resultListener
, when we want to process the input, as long as the external call, the new one Idialogresultlistener pass in, and then implement the Ondataresult () method is ok
The above is the full text of the content, the specific code and examples I put on Github, the need for friends can go to see the Dialogfragmentdemos, if you feel that it is helpful to you, just reward a star!
Guess you like it.
- Teach you how to make a good APP from scratch
- Android can make you less detours of dry cleaning
- Android a very simple, elegant diary APP
Android Roll up sleeves, package yourself dialogfragment