Android XML中引用自定义内部类view的四个why
今天碰到了在XML中应用以内部类形式定义的自定义view,结果遇到了一些坑。虽然通过看了一些前辈写的文章解决了这个问题,但是我看到的几篇都没有完整说清楚why,于是决定做这个总结。
使用自定义内部类view的规则
本文主要是总结why,所以先把XML布局文件中引用内部类的自定义view的做法摆出来,有四点:
- 自定义的类必须是静态类;
- 使用view作为XML文件中的tag,注意,v是小写字母,小写字母v,小写字母v;
- 添加class属性,注意,没有带android:命名空间的,表明该自定义view的完整路径,且外部类与内部类之间用美元“$”连接,而不是“.”,注意,要美元“$”,不要“.”;
- 自定义的view至少应该含有带有Context, AttributeSet这两个参数的构造函数
布局加载流程主要代码
首先,XML布局文件的加载都是使用LayoutInflater来实现的,通过这篇文章的分析,我们知道实际使用的LayoutInflater类是其子类PhoneLayoutInflater,然后通过这篇文章的分析,我们知道view的真正实例化的关键入口函数是createViewFromTag这个函数,然后通过createView来真正实例化view,下面便是该流程用到的关键函数的主要代码:
final Object[] mConstructorArgs = new Object[2]; static final Class<?>[] mConstructorSignature = new Class[] {
Context.class, AttributeSet.class}; //... /**
* Creates a view from a tag name using the supplied attribute set.
* <p>
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* override it.
*
* @param parent the parent view, used to inflate layout params
* @param name the name of the XML tag used to define the view
* @param context the inflation context for the view, typically the
* {@code parent} or base layout inflater context
* @param attrs the attribute set for the XML tag used to define the view
* @param ignoreThemeAttr {@code true} to ignore the {@code android:theme}
* attribute (if set) for the view being inflated,
* {@code false} otherwise
*/
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
//**关键1**//
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
} // Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
} if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
} try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
} if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
} if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
//**关键2**//
view = onCreateView(parent, name, attrs);
} else {
//**关键3**//
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
} return view;
}
//后面都是catch,省略
} protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
return onCreateView(name, attrs);
} protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
} /**
* Low-level function for instantiating a view by name. This attempts to
* instantiate a view class of the given <var>name</var> found in this
* LayoutInflater's ClassLoader.
*
* @param name The full name of the class to be instantiated.
* @param attrs The XML attributes supplied for this instance.
*
* @return View The newly instantiated view, or null.
*/
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null; try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name); if (constructor == null) {
//**关键4**//
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class); if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class); boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
} Object[] args = mConstructorArgs;
args[1] = attrs;
//**关键5**//
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view; }
//后面都是catch以及finally处理,省略
}
PhoneLayoutInflater中用到的主要代码:
public class PhoneLayoutInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
//...... /** Override onCreateView to instantiate names that correspond to the
widgets known to the Widget factory. If we don't find a match,
call through to our super class.
*/
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
//**关键6**//
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// In this case we want to let the base class take a crack
// at it.
}
} return super.onCreateView(name, attrs);
} //.........
}
WHY
对于任何一个XML中的元素,首先都是从“1”处开始(“1”即表示代码中标注“关键1”的位置,后同),下面便跟着代码的流程来一遍:
- “1”处进行名字是否为“view”的判断,那么这里会有两种情况,我们先假设使用“view”
- 由于在“1”满足条件,所以name被赋值为class属性的值,比如“com.willhua.view.MyView”或者“com.willhua.view.MyClass$MyView”。其实这里也是要使用“view”来定义,而不是其他名字来定义的原因。
- 根据name的值,name中含有‘.’符号,于是代码走到“3”处,调用createView,且prefix参数为空
- 来到“4”处,prefix为空,于是loadClass函数的参数即为name,即在a.2中说的class属性的值。我们知道,传给loadClass的参数是想要加载的类的类名,而在Java中,内部类的类名表示都是在外部类类名的后面用符号“$”连接内部类类名而来,于是文章开头提到的第3点的答案也就是在这里了。补充一下,为什么是来到“4”,而不是对应的else块中呢?类第一次被加载的时候,构造器肯定是还不存在的,也就是if条件肯定是成立的。然后等到后面再次实例化的时候,就来到了else块中,而在else快中只是根据mFilter做一些是否可以加载该view的判断而已,并没有从本质上影响view的加载流程。
- 在“4”处还有一个很重要的地方,那就是constructor = class.getConstructor(mConstructorSignature)这句。首先,在代码开头已经给出了mConstructorSignature的定义:
static final Class<?>[] mConstructorSignature = new Class[] {Context.class, AttributeSet.class};
在Oracle的文档上找到getConstructor函数的说明:
Returns a Constructor
object that reflects the specified public constructor of the class represented by this Class
object. The parameterTypes
parameter is an array of Class
objects that identify the constructor's formal parameter types, in declared order. If this Class
object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
The constructor to reflect is the public constructor of the class represented by this Class
object whose formal parameter types match those specified by parameterTypes
.
于是,这里其实解答了我们两个问题:(1)getConstructor返回的构造函数是其参数与传getConstructor的参数完全匹配的那一个,如果没有就抛出NoSuchMethodException异常。于是我们就知道,必须要有一个与mConstructorSignature完全匹配,就需要Context和AttributeSet两个参数的构造函数;(2)要是该类表示的是非静态的内部类,那么应该把一个外部类实例作为第一个参数传入。而我们的代码中传入的mConstructorSignature是不含有外部类实例的,因此我们必须把我们自定义的内部类view声明为静态的才不会报错。有些同学的解释只是说到了非静态内部类需要由一个外部类实例来引用,但我想那万一系统在加载的时候它会自动构造一个外部类实例呢?于是这里给了否定的答案。
6. 拿到了类信息clazz之后,代码来到了“5”,在这里注意下mConstructorArgs,在贴出的代码最前面有给出它的定义,为Object[2],并且,通过源码中发现,mConstructorArgs[0]被赋值为创建LayoutInflater时传入的context。于是我们就知道 在“5”这里,传给newInstance的参数为Context和AttributeSet。然后在Oracl的文档上关于newInstance的说明中也有一句:If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; 我们这里也没有传入外部类实例,也就是说对于静态内部类也会报错。这里同样验证了自定义了的内部类view必须声明为静态类这个问题。
至此,我们已经在假设使用“view”,再次强调是小写‘v’,作为元素名称的情况,推出了要在XML中应用自定义的内部类view必须满足的三点条件,即在class属性中使用“$”连接外部类和内部类,必须有一个接受Context和AttributeSet参数的构造函数,必须声明为静态的这三个要求。
而如果不使用“view”标签的形式来使用自定义内部类view,那么在写XML的时候我们发现,只能使用比如<com.willhua.MyClass.MyView />的形式,而不能使用<com.willhua.MyClass$MyView />的形式,这样AndroidStudio会报“Tag start is not close”的错。显然,如果我们使用<com.willhua.MyClass.MyView />的形式,那么在“关键4”处将会调用loadClass("com.willhua.MyClass.MyView"),这样在前面也已经分析过,是不符合Java中关于内部类的完整命名规则的,将会报错。有些人估计会粗心写成大写的V的形式,即<View class="com.willhua.MyClass$MyView" ... />的形式,这样将会在运行时报“wrong type”错,因为这样本质上定义的是一个android.view.View,而你在代码中却以为是定义的com.willhua.MyClass$MyView。
在标识的“2”处,该出的调用流程为onCreateView(parent, name, attrs)——>onCreateView(name, attrs)——>createView(name, "android.view.", attrs),在前面提到过,我们真正使用的的LayoutInflater是PhoneLayoutInflater,而在PhoneLayoutInflater对这个onCreateView(name, attrs)函数是进行了重写的,在PhoneLayoutInflater的onCreateView函数中,即“6”处,该函数通过在name前面尝试分别使用三个前缀:"android.widget.","android.webkit.","android.app."来调用createView,若都没有找到则调用父类的onCreateView来尝试添加"android.view."前缀来加载该view。所以,这也是为什么我们可以比如直接使用<Button />, <View />的原因,因为这些常用都是包含在这四个包名里的。
总结
至此,开篇提到的四个要求我们都已经找到其原因了。其实,整个流程走下来,我们发现,要使定义的元素被正确的加载到相关的类,有三种途径:
- 只使用简单类名,即<ViewName />的形式。对于“android.widget”, "android.webkit", "android.app"以及"android.view"这四个包内的类,可以直接使用这样的形式,因为在代码中会自动给加上相应的包名来构成完整的路径,而对于的其他的类,则不行,因为ViewName加上这四个包名构成的完整类名都无法找到该类。
- 使用<"完整类名" />的形式,比如<com.willhua.MyView />或者<android.widget.Button />的形式来使用,对于任何的非内部类view,这样都是可以的。但是对于内部类不行,因为这样的类名不符合Java中关于内部类完整类名的定义规则。如果<com.willhua.MyClass$MyView />的形式能够通过编译话,肯定是能正确Inflate该MyView的,可惜在编写的时候就会提示错。
- 使用<view class="完整类名" />的形式。这个是最通用的,所有的类都可以这么干,但是前提是“完整类名”写对,比如前面提到的内部类使用"$"符号连接。
为了搞清楚加载内部类view的问题,结果对整个加载流程都有了一定了解,感觉能说多若干个why了,还是收获挺大的。
参考:
http://blog.csdn.net/gorgle/article/details/51428515
http://blog.csdn.net/abcdef314159/article/details/50921160
http://blog.csdn.net/abcdef314159/article/details/50925124
周末愉快~~~
Android XML中引用自定义内部类view的四个why的更多相关文章
- Android自定义View研究--View中的原点坐标和XML中布局自定义View时View触摸原点问题
这里只做个汇总~.~独一无二 文章出处:http://blog.csdn.net/djy1992/article/details/9715047 Android自定义View研究--View中的原点坐 ...
- Android studio 中引用jar的其实是Maven?(二)
上一篇:Android studio 中引用jar的其实是Maven?(一) 搭建maven仓库: 去了解一个新的事物的时候,最好的方式就是去使用它.例如去了解一座城市的时候,最好的方式就是乘坐公共交 ...
- C程序中引用自定义的C函数模块
原文:C程序中引用自定义的C函数模块 我们知道,刚开始接触C语言编程,一般都是在一个.c或者.cpp(以下只说.c)的文件中编写代码,其中一定会有一个入口函数, 也就是main()函数,你可以将程序代 ...
- Android studio 中引用jar的其实是Maven?(一)
由于Studio比eclipse多了一步对工程构建的步骤,即为build.gradle这个文件运行,因此其引入第三方开发jar包与lib工程对比Eclipse已完成不同,引入第三方jar与lib工程显 ...
- Dojo初探之2:设置dojoConfig详解,dojoConfig参数详解+Dojo中预置自定义AMD模块的四种方式(基于dojo1.11.2)
Dojo中想要加载自定义的AMD模块,需要先设置好这个模块对应的路径,模块的路径就是这个模块的唯一标识符. 一.dojoConfig参数设置详解 var dojoConfig = { baseUrl: ...
- 【转】 Android xml中 @和?区别,style和attr小结
引用资源时,使用@还是?的区别,例如在设置style的时候既可以使用@也可以使用? style="?android:attr/progressBarStyleHorizontal" ...
- android xml中使用include标签
在一个项目中,我们可能会在xml中局部用到相同的布局,如果每次都在xml中重写这些布局,代码显得很冗余.重复的复制黏贴也很烦恼,所以,我们把这些相同的局部布局写成一个单独的xml模块,需要用到这些布局 ...
- Android应用中使用自定义文字
在Android系统中可以很方便的修改字体样式.系统提供了三种样式,分别是sans,serif,monospace.可以在xml布局文件中通过 android:typeface="[sans ...
- Android项目中引用到其他工程
有的时候我们需要在现有的项目中引用到其他项目的资源和文件,当然我们可以将被引用的工程打成jar包,但是这有个缺点就是,这个改动比较麻烦,除非是被引用的工程的资源和源程序文件不再改动,可以这样做,否则每 ...
随机推荐
- 【腾讯Bugly干货分享】H5 视频直播那些事
本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/57a42ee6503dfcb22007ede8 Dev Club 是一个交流移动 ...
- Hadoop学习笔记系列文章导航
一.为何要学习Hadoop? 这是一个信息爆炸的时代.经过数十年的积累,很多企业都聚集了大量的数据.这些数据也是企业的核心财富之一,怎样从累积的数据里寻找价值,变废为宝炼数成金成为当务之急.但数据增长 ...
- UWP开发:APP之间的数据交互(以微信为例)
目录 说明 UWP应用唤醒方式 跟微信APP交互数据 APP之间交互数据的前提 说明 我们经常看到,在手机上不需要退到桌面,APP之间就可以相互切换,并且可以传递数据.比如我在使用知乎APP的时候,需 ...
- 浅谈命令查询职责分离(CQRS)模式
在常用的三层架构中,通常都是通过数据访问层来修改或者查询数据,一般修改和查询使用的是相同的实体.在一些业务逻辑简单的系统中可能没有什么问题,但是随着系统逻辑变得复杂,用户增多,这种设计就会出现一些性能 ...
- Atitit. 破解 拦截 绕过 网站 手机 短信 验证码 方式 v2 attilax 总结
Atitit. 破解 拦截 绕过 网站 手机 短信 验证码 方式 v2 attilax 总结 1. 验证码的前世今生11.1. 第一代验证码 图片验证码11.2. 第二代验证码 用户操作 ,比如 ...
- 基于Caffe的Large Margin Softmax Loss的实现(中)
小喵的唠叨话:前一篇博客,我们做完了L-Softmax的准备工作.而这一章,我们开始进行前馈的研究. 小喵博客: http://miaoerduo.com 博客原文: http://www.miao ...
- .Net中的RealProxy实现AOP
序言 这个AOP要从我们公司的一个事故说起,前段时间公司的系统突然在乌云中出现,数据被泄露的一览无余,乌云上显示是SQL注入攻击.呵,多么贴近生活的一个露洞,可谓是人尽皆知啊.然而却华丽丽的给拉我们一 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(48)-工作流设计-起草新申请
系列目录 创建新表单之后,我们就可以起草申请了,申请按照严格的表单步骤和分支执行. 起草的同时,我们分解流转的规则中的审批人并保存,具体流程如下 接下来创建DrafContoller控制器,此控制器只 ...
- MySQL binlog中的事件类型
MySQL binlog记录的所有操作实际上都有对应的事件类型的,譬如STATEMENT格式中的DML操作对应的是QUERY_EVENT类型,ROW格式下的DML操作对应的是ROWS_EVENT类型. ...
- 3、C#核心编程结构下
本学习主要参考Andrew Troelsen的C#与.NET4高级程序设计,这小节主要述说以下几个东西: 这一小节是上一小节的补充,主要涉及到一下的知识细节: 1.C#方法的各种细节 2.探讨out ...