Android中Window添加View的底层原理

2019-12-10 18:54:25刘景俊

void makeVisible() { 
   if (!mWindowAdded) { 
     ViewManager wm = getWindowManager(); 
     wm.addView(mDecor, getWindow().getAttributes()); 
     mWindowAdded = true; 
   } 
   mDecor.setVisibility(View.VISIBLE); 
 } 

通过上面的addView方法将View添加到Window。
三、Window操作View内部机制
1.window的添加
一个window对应一个view和一个viewRootImpl,window和view通过ViewRootImpl来建立联系,它并不存在,实体是view。只能通过 windowManager来操作它。
windowManager的实现类是windowManagerImpl。它并没有直接实现三大操作,而是委托给WindowManagerGlobal。addView的实现分为以下几步:
1).检查参数是否合法。

if (view == null) { 
      throw new IllegalArgumentException("view must not be null"); 
    } 
    if (display == null) { 
      throw new IllegalArgumentException("display must not be null"); 
    } 
    if (!(params instanceof WindowManager.LayoutParams)) { 
      throw new IllegalArgumentException("Params must be WindowManager.LayoutParams"); 
    } 
 
    final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params; 
    if (parentWindow != null) { 
      parentWindow.adjustLayoutParamsForSubWindow(wparams); 
    } else { 
      // If there's no parent and we're running on L or above (or in the 
      // system context), assume we want hardware acceleration. 
      final Context context = view.getContext(); 
      if (context != null 
          && context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) { 
        wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED; 
      } 
    } 

2).创建ViewRootImpl并将View添加到列表中。

root = new ViewRootImpl(view.getContext(), display); 
 
      view.setLayoutParams(wparams); 
 
      mViews.add(view); 
      mRoots.add(root); 
      mParams.add(wparams);