SetContentView 到底Set去哪里呢?

学一门新的语言或者技术,一般都 从HelloWorld开始的,我们学习Android也是一样的,

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

在我们的MainActivity中,只要这样简单地调用setContentView就可以将main里面的东西给显示在手机界面上了。

很简单的东西,所以都没有怎么去想过为什么这样调用setContentView就可以了,直到今天。

今天,看了几篇博客,讲到了View是如何绘制的,及setContentView是如何开始的,才发现自己思维太简单了,只想着用而用,没有去思考为什么这么用就可以,缺乏总结。

所以觉得还是得先记录一下自己的理解。

我们都知道,在手机界面上,我们要展现Button,TextView, ImageView等控件,我们必须将其放在一个布局,可以是我们自定义的布局,也可以是Android本身 提供的布局。

但是,这所有的布局,其实最终都是放在一个叫DecorView的最顶层,最外层的FrameLayout上。

Android本身提供了一些布局,比如最常见的R.layout.screen_title,包含有Title (标题栏) 和 Content(内容)的一个布局,如果我们没有设置什么Feature 之类的属性,一般就是用这个layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:fitsSystemWindows="true">
        <FrameLayout
            android:layout_width="match_parent" 
            android:layout_height="?android:attr/windowTitleSize"
            style="?android:attr/windowTitleBackgroundStyle">
            <TextView android:id="@android:id/title" 
                style="?android:attr/windowTitleStyle"
                android:background="@null"
                android:fadingEdge="horizontal"
                android:gravity="center_vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </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的时候,其实是调用对应Window类(具体是PhoneWindow类)的setConentView,在这个方法中,会去初始化DecorView, 并根据之前设定的Feature属性,选择一个layout(比如R.layout_screen_title),将其添加到DecorView中,并获取其中的content子视图。

如上面所示,其实Title所对应的FrameLayout 就是标题栏, Content 所对应的FrameLayout 就是内容布局。我们自定义的main.xml 其实就是展示在这个Content 上。

大概结构如下:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值