Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a Dialog View integrate with its Activity's view Hierarchy

Tags:

java

android

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.

like image 534
LazyBoy Avatar asked Jul 02 '14 20:07

LazyBoy


1 Answers

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.

like image 158
matiash Avatar answered Oct 06 '22 01:10

matiash