学习自定义View一段时间了,从开始的一窍不通到现在终于能写出点东西了,前面也写过几篇关于自定义view的博客,但是感觉这东西吧,一天不敲又忘记了,所以准备写一篇自定义View系列的博客,这也算是我这段时间学习自定义View总结的开篇,接下来还会有一系列的文章,支持我的朋友可以悄悄的点个赞,一起fighting!!!
既然是总结性的东西我们就要研究透一点,我们从源码看,不啰嗦了,开车了……
首先获取LayoutInflater的方式有两种:
方式一:
LayoutInflater inflater = LayoutInflater.from(context);
方式二:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
其实方式一的from方法里面就是通过方式二的方式实现的
*
* Obtains the LayoutInflater from the given context.
*/
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
好了,讲了怎么获取LayoutInflater实例了,我们该研究下inflater方法了,
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
可以看了inflater中需要传递三个参数,
Tables | Are |
---|---|
resource | 需要inflater的layout文件 |
root | root布局 |
attachToroot | 是否加到root布局中 |
先大致走一遍源码,
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new Infla