您的位置:首页 > 产品设计 > UI/UE

Android UI源码解析

2016-03-14 00:00 519 查看
摘要: Android开发很大一部分都是在用户体验上需要提高,衍生的Android开发UI布局有直接的关系,这里需要简介一下Android底层加载UI布局文件

首先我们从activity中的oncreate中的setContentView()方法介绍:

在Window 抽象类中有三个setContentView的方法,Window类有是Activity的成员属性

PhoneWindow继承了Window 实现了setContentView方法, 在PhoneWindow类中还有内部类DecorView

DecorView继承了Framelayout 是一个具体现实View容器。



在PhoneWindow中实现setContentView具体方法:

(layoutResID) {
(== ) {
installDecor()} (!hasFeature()) {
.removeAllViews()}

(hasFeature()) {
Scene newScene = Scene.(layoutResIDgetContext())transitionTo(newScene)} {
.inflate(layoutResID)}
Callback cb = getCallback()(cb != && !isDestroyed()) {
cb.onContentChanged()}
}

首先判断了mContentparent 是否为空,这个就是xml文件的根节点

mLayoutInflater.inflate(layoutResID, mContentParent);将我们的资源文件通过LayoutInflater对象转换为View树,并且添加至mContentParent视图中(其中mLayoutInflater是在PhoneWindow的构造函数中得到实例对象的
LayoutInflater.from(context);
)。

再来看下PhoneWindow类的setContentView(View view)方法和setContentView(View view, ViewGroup.LayoutParams params)方法源码:

(View viewViewGroup.LayoutParams params) {
(== ) {
installDecor()} (!hasFeature()) {
.removeAllViews()}

(hasFeature()) {
view.setLayoutParams(params)Scene newScene = Scene(view)transitionTo(newScene)} {
.addView(viewparams)}
Callback cb = getCallback()(cb != && !isDestroyed()) {
cb.onContentChanged()}
}

直接分析setContentView(View view, ViewGroup.LayoutParams params)方法就行,可以看见该方法与setContentView(int layoutResID)类似,只是少了LayoutInflater将xml文件解析装换为View而已,这里直接使用View的addView方法追加道了当前mContentParent而已。

所以说在我们的应用程序里可以多次调用setContentView()来显示界面,因为会removeAllViews。

我们先看一下源码中LayoutInflater实例化获取的方法

LayoutInflater (Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.)(LayoutInflater == ) {
AssertionError()}
LayoutInflater}


获取
LayoutInflater
实例的三种方式:


// 方式1

// 调用Activity的getLayoutInflater()

LayoutInflater inflater = getLayoutInflater();

// 方式2

LayoutInflater inflater = LayoutInflater.from(context);

// 方式3

LayoutInflater inflater = LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android UI SetContentView