AndroidXML中引用自定义内部类view的四个why
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,下面便是该流程用到的关键函数的主要代码:
复制代码
1 final Object[] mConstructorArgs = new Object[2];
2
3 static final Class>[] mConstructorSignature = new Class[] {
4 Context.class, AttributeSet.class};
5
6 //...
7
8 /**
9 * Creates a view from a tag name using the supplied attribute set.
10 *
11 * Note: Default visibility so the BridgeInflater can
12 * override it.
13 *
14 * @param parent the parent view, used to inflate layout params
15 * @param name the name of the XML tag used to define the view
16 * @param context the inflation context for the view, typically the
17 * {@code parent} or base layout inflater context
18 * @param attrs the attribute set for the XML tag used to define the view
19 * @param ignoreThemeAttr {@code true} to ignore the {@code android:theme}
20 * attribute (if set) for the view being inflated,
21 * {@code false} otherwise
22 */
23 View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
24 boolean ignoreThemeAttr) {
25 //**关键1**//
26 if (name.equals("view")) {
27 name = attrs.getAttributeValue(null, "class");
28 }
29
30 // Apply a theme wrapper, if allowed and one is specified.