我是靠谱客的博主 勤奋板栗,这篇文章主要介绍从零开始理解Android下View(一)----学习笔记(参考郭霖大神博客),现在分享给大家,希望可以做个参考。

参考链接:郭神博客

Android下Activity中加载布局一般是通过setContentView()方法实现的,而setContentView()其实是通过调用LayoutInflater实现的。
要研究LayoutInflater原理,首先就要获取它的实例,有两种方法可以拿到LayoutInflater的实例:

复制代码
1
2
3
4
5
//第一种方法 LayoutInflater inflater = LayoutInflater.from(context); //第二种方法 LayoutInflater inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

其中方法一相当于对方法二进行了一次封装。
inflater的基本使用就不在详细说,直接放通过LayoutInflater加载按钮的代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainActivity extends Activity { private LinearLayout mainLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainLayout = (LinearLayout) findViewById(R.id.main_layout); LayoutInflater layoutInflater = LayoutInflater.from(this); View buttonLayout = layoutInflater.inflate(R.layout.button_layout, null); mainLayout.addView(buttonLayout); } }

可以看到LayoutInflater是通过调用inflater实现功能的,那么inflater()是如何实现的呢?
inflater()其实有多个重载,不过最终都会调用到下面这个实现:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { final AttributeSet attrs = Xml.asAttributeSet(parser); mConstructorArgs[0] = mContext; View result = root; try { int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } final String name = parser.getName(); if (TAG_MERGE.equals(name)) { if (root == null || !attachToRoot) { throw new InflateException("merge can be used only with a valid " + "ViewGroup root and attachToRoot=true"); } rInflate(parser, root, attrs); } else { View temp = createViewFromTag(name, attrs); ViewGroup.LayoutParams params = null; if (root != null) { params = root.generateLayoutParams(attrs); if (!attachToRoot) { temp.setLayoutParams(params); } } rInflate(parser, temp, attrs); if (root != null && attachToRoot) { root.addView(temp, params); } if (root == null || !attachToRoot) { result = temp; } } } catch (XmlPullParserException e) { InflateException ex = new InflateException(e.getMessage()); ex.initCause(e); throw ex; } catch (IOException e) { InflateException ex = new InflateException( parser.getPositionDescription() + ": " + e.getMessage()); ex.initCause(e); throw ex; } return result; } }

通过代码我们很容易发现inflater()方法本质上是基于Pull方法去解析XML布局文件的。

最后

以上就是勤奋板栗最近收集整理的关于从零开始理解Android下View(一)----学习笔记(参考郭霖大神博客)的全部内容,更多相关从零开始理解Android下View(一)----学习笔记(参考郭霖大神博客)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部