findViewById源码解析

本文深入解析了Android中findViewById方法的工作原理,从源码层面解释了如何通过资源ID查找并返回对应的View组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一直都在用findViewById来初始化view,但不知道里面具体的实现,先看下findViewById源码。

public final View findViewById(@IdRes int id) {
    if (id < 0) {
        return null;
    }
    return findViewTraversal(id);
}

最后调用findViewTraversal方法。

protected View findViewTraversal(@IdRes int id) {
    if (id == mID) {
        return this;
    }
    return null;
}

可以看出如果id相等就直接返回这个view,因为一般是viewgroup使用findViewById,所以viewgroup应该重写了这个方法。

protected View findViewTraversal(@IdRes int id) {
    if (id == mID) {
        return this;
    }
    final View[] where = mChildren;
    final int len = mChildrenCount;
    for (int i = 0; i < len; i++) {
        View v = where[i];
        if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
            v = v.findViewById(id);
            if (v != null) {
                return v;
            }
        }
    }
    return null;
}

可以看出viewGroup的id等于要找的id直接返回viewGroup子类,不等于的话就遍历viewGoup包含的view。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值