I am quite new to Android, and while trying to understand how dialogs work, I had this below question. For an Activity, once the View Hierarchy is set through setContentView(View), the View hierarchy cannot be changed unless the activity is recreated. This is the reason Activities are recreated on Rotating the devices, so that new View hierarchy layouts can be utilized. However assuming the above statements are true, then how does a Dialog fit in the Activities view Hierarchy, when they are created? They just appear floating above the Activity window, with having no apparent space in the Activities view hierarchy? Although certainly they are somehow linked with the activity, as getActivity() methods returns a valid Activity instance. Any pointers or clarification will really be appreciated.
A dialog isn't actually a part of the activity's view hierarchy. Dialogs are added via the WindowManager
.
Check the source code for Dialog
. When the Dialog is instantiated, it obtains a reference to the WindowManager from the context, and initializes a new Window.
mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Window w = PolicyManager.makeNewWindow(mContext);
Then later, when you show()
the Dialog:
WindowManager.LayoutParams l = mWindow.getAttributes();
try {
mWindowManager.addView(mDecor, l);
mShowing = true;
When you call setContentView()
, the view you supply is attached to the activity's default window. When you call Dialog.show()
, the dialog's view is attached to a different window for the same display. That's why they are both displayed without actually being part of the same view hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With