Android: Custom DialogFragment content and buttons
Minor issues, record down ~
We recommend that you replace DialogFragment with Dialog after Android4.0. Two examples are provided in the official Android documentation:
One
Basic Dialog
This example shows how to customize window content -- rewrite
onCreateView
Method. One
Alert Dialog
This example shows how to customize the plus or minus buttons in the pop-up window -- rewrite
onCreateDialog
Method. Okay, so the question is.
In practical applications, you often need to customize the window content and buttons.
At this time, if we rewrite the onCreateView and onCreateDialog methods of DialogFragment, we will find -- Bong! Exception ~ Such as "AndroidRuntimeException: requestFeature () must be called before adding content.
For the cause of this exception, see the answer of Freerider in stackoverflow and the comments below.
Excerpt: "You can override both (in fact the DialogFragment says so), the problem comes when you try to inflate the view after having already creating the dialog view. you can still do other things in onCreateView, like use the savedInstanceState, without causing the exception."
Then there is the solution:
Since the two methods cannot be rewritten at the same time, select one method for rewriting:
Override the onCreateDialog method, refer to the official example to customize the button, and then modify it so that you can customize the view -- In AlertDialog. Buildercreate()
Before creating a dialog, usesetView(view)
Method, where view is a custom view.
To see the difference ~
This is an example from Google:
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) { int title = getArguments().getInt(title); return new AlertDialog.Builder(getActivity()) .setIcon(R.drawable.alert_dialog_icon) .setTitle(title) .setPositiveButton(R.string.alert_dialog_ok, 。。。) .setNegativeButton(R.string.alert_dialog_cancel, 。。。) .create();}
This is after modification:
@ Overridepublic Dialog onCreateDialog (Bundle savedInstanceState) {// inflater instantiate View v = inflater in the previous constructor. inflate (R. layout. dialog, null); imageGridView = (GridView) v. findViewById (R. id. gridViewImage); // custom view, bla ~ Bla ~ AlertDialog. builder builder = new AlertDialog. builder (getActivity (); return builder. setView (v ). setIcon (android. r. drawable. ic_dialog_alert ). setTitle (title ). setCancelable (false ). setPositiveButton (R. string. alert_dialog_ OK ,...) . SetNegativeButton (R. string. alert_dialog_cancel ,...) . Create ();}