一、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