android setContentView()原理

转载请说明来自:http://blog.csdn.net/super_kingking/article/details/52486966
在activity加载布局的时候我们会用到setContentView()自定义的布局文件,我们来了解一下setContentView()是怎样把布局文件加载进去的。

首先进入activity看一下代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

进入setContentView():

 public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

调用getWindow().setContentView(layoutResID);getwindow()是什么,public abstract class Window 可以看到window是个抽象方法,查找其子类phoneWindow

phoneWindow.java

   public void setContentView(int layoutResID)
    {
        if(mContentParent == null)
        {
            installDecor();
        } else
        {
            mContentParent.removeAllViews();
            updateInflateParams();
        }
        mViewInflate.inflate(layoutResID, mContentParent, mInflateParams);
        android.view.Window.Callback cb = getCallback();
        if(cb != null)
            cb.onContentChanged();
    }

首先判断mContentParent 是否存在,如果不存在调用installDecor();那installDecor()是干嘛的呢,大家试想一下如果mContentParent 不存在,那installDecor()就应该是让mContentParent 存在的。

进入installDecor()方法:

  private void installDecor()
    {
        if(mDecor == null)
        {
            mDecor = generateDecor();
            mDecor.setIsRootNamespace(true);
        }
        if(mContentParent == null)
        {
            mContentParent = generateLayout(mDecor);
            mTitleView = (TextView)findViewById(0x1050012);
            if(mTitleView != null)
                if((getLocalFeatures() & 2) != 0)
                {
                    View titleContainer = findViewById(0x1050013);
                    if(titleContainer != null)
                        titleContainer.setVisibility(8);
                    else
                        mTitleView.setVisibility(8);
                    if(mContentParent instanceof FrameLayout)
                        ((FrameLayout)mContentParent).setForeground(null);
                } else
                {
                    mTitleView.setText(mTitle);
                }
        }
    }

第5行创建了mDecor 对象,mDecor 的DecorView的对象,是phonewindow的内部类,继承于FrameLayout
第10行创建mContentParent 对象时并把mDecor 传了进去。mDecor 和mContentParent 二者的关系呢?

查看代码generateLayout(mDecor)的方法:

protected ViewGroup generateLayout(DecorView decor) {  
    // Apply data from current theme.  
   //获取window属性
    TypedArray a = getWindowStyle();  
    if (false) {  
        System.out.println("From style:");  
        String s = "Attrs:";  
        for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) {  
            s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "="  
                    + a.getString(i);  
        }  
        System.out.println(s);  
    }  
    //判断窗口是否浮动
    mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);  
    int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)  
            & (~getForcedWindowFlags());  
    if (mIsFloating) {  
        setLayout(WRAP_CONTENT, WRAP_CONTENT);  
        setFlags(0, flagsToUpdate);  
    } else {  
        setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);  
    }  

    //判断窗口是否有标题
    if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {  
        requestFeature(FEATURE_NO_TITLE);  
    }  
    //判断窗口是否满屏
    if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {  
        setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags()));  
    }  
    //判断窗口是否
    if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {  
        setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));  
    }  
    WindowManager.LayoutParams params = getAttributes();  
//设置输入法模式
    if (!hasSoftInputMode()) {  
        params.softInputMode = a.getInt(  
                com.android.internal.R.styleable.Window_windowSoftInputMode,  
                params.softInputMode);  
    }  
    if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled,  
            mIsFloating)) {  
        /* All dialogs should have the window dimmed */  
        if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {  
            params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;  
        }  
        params.dimAmount = a.getFloat(  
                android.R.styleable.Window_backgroundDimAmount, 0.5f);  
       //动画
    }  
    if (params.windowAnimations == 0) {  
        params.windowAnimations = a.getResourceId(  
                com.android.internal.R.styleable.Window_windowAnimationStyle, 0);  
    }  
    // The rest are only done if this window is not embedded; otherwise,  
    // the values are inherited from our container.  
    if (getContainer() == null) {  
        if (mBackgroundDrawable == null) {  
            if (mBackgroundResource == 0) {  
                mBackgroundResource = a.getResourceId(  
                        com.android.internal.R.styleable.Window_windowBackground, 0);  
            }  
            if (mFrameResource == 0) {  
                mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0);  
            }  
            if (false) {  
                System.out.println("Background: "  
                        + Integer.toHexString(mBackgroundResource) + " Frame: "  
                        + Integer.toHexString(mFrameResource));  
            }  
        }  
        mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000);  
    }  
    **以上都是设置一些window的属性,这里也说明设置window属性要在setContentView()之前设置的原因了。**

    // Inflate the window decor.  

    **//下面是根据各种情况设置layoutResource**

    int layoutResource;  
    int features = getLocalFeatures();  
    // System.out.println("Features: 0x" + Integer.toHexString(features));  
    if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {  
        if (mIsFloating) {  
            layoutResource = com.android.internal.R.layout.dialog_title_icons;  
        } else {  
            layoutResource = com.android.internal.R.layout.screen_title_icons;  
        }  
        // System.out.println("Title Icons!");  
    } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0) {  
        // Special case for a window with only a progress bar (and title).  
        // XXX Need to have a no-title version of embedded windows.  
        layoutResource = com.android.internal.R.layout.screen_progress;  
        // System.out.println("Progress!");  
    } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {  
        // Special case for a window with a custom title.  
        // If the window is floating, we need a dialog layout  
        if (mIsFloating) {  
            layoutResource = com.android.internal.R.layout.dialog_custom_title;  
        } else {  
            layoutResource = com.android.internal.R.layout.screen_custom_title;  
        }  
    } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {  
        // If no other features and not embedded, only need a title.  
        // If the window is floating, we need a dialog layout  
        if (mIsFloating) {  
            layoutResource = com.android.internal.R.layout.dialog_title;  
        } else {  
            layoutResource = com.android.internal.R.layout.screen_title;  
        }  
        // System.out.println("Title!");  
    } else {  
        // Embedded, so no decoration is needed.  
        layoutResource = com.android.internal.R.layout.screen_simple;  
        // System.out.println("Simple!");  
    }  
    mDecor.startChanging();  


    View in = mLayoutInflater.inflate(layoutResource, null);  
    //将layoutResource转化成View添加到decor中,
    decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));  
//然后又通过findViewById找到该view,

    ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);  
    if (contentParent == null) {  
        throw new RuntimeException("Window couldn't find content container view");  
    }  
    if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {  
        ProgressBar progress = getCircularProgressBar(false);  
        if (progress != null) {  
            progress.setIndeterminate(true);  
        }  
    }  
    // Remaining setup -- of background and title -- that only applies  
    // to top-level windows.  
    if (getContainer() == null) {  
        Drawable drawable = mBackgroundDrawable;  
        if (mBackgroundResource != 0) {  
            drawable = getContext().getResources().getDrawable(mBackgroundResource);  
        }  
        mDecor.setWindowBackground(drawable);  
        drawable = null;  
        if (mFrameResource != 0) {  
            drawable = getContext().getResources().getDrawable(mFrameResource);  
        }  
        mDecor.setWindowFrame(drawable);  
        // System.out.println("Text=" + Integer.toHexString(mTextColor) +  
        // " Sel=" + Integer.toHexString(mTextSelectedColor) +  
        // " Title=" + Integer.toHexString(mTitleColor));  
        if (mTitleColor == 0) {  
            mTitleColor = mTextColor;  
        }  
        if (mTitle != null) {  
            setTitle(mTitle);  
        }  
        setTitleColor(mTitleColor);  
    }  
    mDecor.finishChanging();  
    //然后返回
    return contentParent;  

} 

//通过inflate解析view,如果大家想对inflate更深入的了解可以参考http://blog.csdn.net/super_kingking/article/details/51983011
关于layoutResource可以在frameworks\base\core\res\res\layout里面进行查看。
例如:R.layout.screen_custom_title.xml文件如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:fitsSystemWindows="true">  
    <!-- Popout bar for action modes -->  
    <ViewStub android:id="@+id/action_mode_bar_stub"  
              android:inflatedId="@+id/action_mode_bar"  
              android:layout="@layout/action_mode_bar"  
              android:layout_width="match_parent"  
              android:layout_height="wrap_content" />  

    <FrameLayout android:id="@android:id/title_container"   
        android:layout_width="match_parent"   
        android:layout_height="?android:attr/windowTitleSize"  
        style="?android:attr/windowTitleBackgroundStyle">  
    </FrameLayout>  
    <FrameLayout android:id="@android:id/content"  
        android:layout_width="match_parent"   
        android:layout_height="0dip"  
        android:layout_weight="1"  
        android:foregroundGravity="fill_horizontal|top"  
        android:foreground="?android:attr/windowContentOverlay" />  
</LinearLayout>```

接着看activity的setContentView的源码

@Override  
  public void setContentView(int layoutResID) {  
      if (mContentParent == null) {  
          installDecor();  
      } else {  
          mContentParent.removeAllViews();  
      }  
      mLayoutInflater.inflate(layoutResID, mContentParent);  
      final Callback cb = getCallback();  
      if (cb != null && !isDestroyed()) {  
          cb.onContentChanged();  
      }  
  }

获得了mContentParent后,将setContentView(layoutResID)的layoutResID通过 mLayoutInflater.inflate(layoutResID, mContentParent); 添加到mContentParent中。

总结:setContentView(layoutResID)是先通过phoneWindow的内部类(frameLayout的子类)DecorView的创建对象mDecor,再去创建contentParent(也是Framelayout的子类,id=content) ,通过findViewByID找到并返回,最后将setContentView(layoutResID)的layoutResID添加到contentParent中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值