深入理解findViewById()
来源:互联网 发布:平安科技 大数据应用 编辑:程序博客网 时间:2024/06/05 20:41
一、Activity中的findViewById()和View中的findViewById()区别
先获取一个Window对象,再获取一个顶层View(可能是View也可能是ViewGroup)对象,再调用View(ViewGroup)的findViewById()方法;调用View(ViewGroup)的findViewById()方法是一个递归过程。
二、布局文件activity_main.xml示例
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/top_layout"> <LinearLayout android:id="@+id/inner_layout1" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"> </LinearLayout> <LinearLayout android:id="@+id/inner_layout2" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/editText1" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="Input Something"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:textAllCaps="false"/> </LinearLayout></LinearLayout>
三、源码分析
1.Activity中的findViewById()方法:
@Nullable public View findViewById(@IdRes int id) { return getWindow().findViewById();}先获取一个Window对象
2.Window中的findViewById()方法:
@Nullable public View findViewById(@IdRes int id) { return getDecorView().findViewById(id); }再获取一个顶层View(可能是View也可能是ViewGroup)对象,再调用View(ViewGroup)的findViewById()方法;调用ViewGroup(View)的findViewById()方法是一个递归过程。
3.View(ViewGroup)中的findViewById()方法:
@Nullable public final View findViewById(@IdRes int id) { if (id < 0) { return null; } return findViewTraversal(id); }
ViewGroup(View)的findTraversal()方法:
protected View findViewTraversal(@IdRes int id) { if (id == mID) {//查找成功 return this; } final View[] where = mChildren; final int len = mChildrenCount; //循环,若为ViewGroup,执行循环;若为View,mChildrenCount为0,不执行循环 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; }转自:http://blog.csdn.net/daiyibo123/article/details/50949580#comments
阅读全文
0 0
- 深入理解findViewById()
- 深入理解findViewById原理
- [android]深入理解findViewById原理
- LayoutInflater与findViewById()
- FindViewById
- findViewById
- findViewById
- findViewById
- findViewById
- findViewById
- Android-findViewById()方法分析
- [*****]深入理解计算机系统(修订版)
- 深入理解Image.createImage()
- 《深入理解计算机系统(修订版)》
- 深入理解Image.createImage()
- 深入理解Image.createImage()
- 深入理解Image.createImage()
- 深入理解Image.createImage()
- Redis笔记(三)Redis的数据类型
- css3选择器
- python 接口自动化测试(三)
- 阿里云自研云数据库POLARDB_未来企业的数字化答案
- 利用递归实现折半查找
- 深入理解findViewById()
- org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session f
- 迷宫的实现
- typelayout+Xlistview
- Redis笔记(五)Redis的事务
- Echarts使用示例
- iOS开发-随机图片验证码
- Android接口回调机制
- 反射机制获取Class对象的三种方式