android定义内部类,AndroidXML中引用自定义内部类view的四个why.doc

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值