Layout的加载流程及⼿写百分⽐布局百分⽐布局
其实⾕歌为开发者提供了 PercentRelativeLayout 百分⽐布局,它继承⾃RelativeLayout
下⾯我们就来简单使⽤它
在adle中引⽤implementation 'com.android.support:percent:28.0.0'
在布局⽂件中使⽤它
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout xmlns:android="schemas.android/apk/res/android"    xmlns:app="schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:text="百分百布局"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
margin属性值可以为百分比</android.support.percent.PercentRelativeLayout>
宽,⾼ 各占百分之50% ,看看效果
接下来,我们⾃⼰ 写⼀个 类似于 PercentRelativeLayout 的容器
在此之前我们需要了解⼀下 布局⽂件 layout 的加载流程,我们在⼦view中设置的属性 在什么时候被解析的,
什么时候被使⽤的 下⾯我们就以 RelativeLayout 来说明,它的⼦view TextviewT设置的属性什么时候被解析的,什么时候
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="schemas.android/apk/res/android"
xmlns:app="schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="@color/colorAccent"
android:text="百分百布局"
/>
</RelativeLayout>
⾸先我们使⽤该 Layout 布局⽂件时 是通过Activity的setContentView使⽤的
我们再进⼊到setContentView 的源码⾥⾯看看
可以看到 ⼜调⽤的是 getWindow().setContentView(layoutResID); ,把布局传了进去,那这个getWindow ()是什么了?
可以看到这个⽅法返回的是⼀个mWindow 对象,那么我们再看看这个对象是什么?
可以看到这是⼀个Window 类的对象引⽤,点点进去看看这个Window 类
我们可以看到,这个Window 类是⼀个抽象类,从上⾯的注释翻译来看,它仅存在唯⼀⼦类 PhoneWindow,也就是说,PhoneWindow就是Window 的唯⼀实现⼦类
所以 getWindow().setContentView(layoutResID)最终调⽤到的是PhoneWindow类⾥⾯的 setContentView(int layoutResID)⽅法,把我们的布局⽂件传到了这⾥
我们此时注意到了  mLayoutInflater.inflate(layoutResID, mContentParent); 这⾏代码,它是加载我们布局⽂件 layoutResID 跟踪该⽅法,它调⽤的是这个⽅法
我们再进⼊这个 inflate ⽅法
final XmlResourceParser parser = Layout(resource);
此时已经开始解析我们的布局⽂件了
接着继续调⽤ return inflate(parser, root, attachToRoot); 这⾏代码
我们进⼊这个⽅法
⽅法的开头是在获取⼀些节点信息,我们往⽅法的下⾯⾛