view.getParent(),view.getRootView()
先写结论如下,再用两个简单示例让你更容易理解
结论
- 如果该View是View树的根节点,getParent()返回null,
- 如果该View是View树的非根节点,getParent()返回其父View
- getRootView始终返回View树的根View
示例
- 针对Activity,无论使用什么布局,整体结构都可以使用如下图所示

- 非根节点也就是非DecorView,其getParent()一定是它的父View,DecorView是View树中根节点,其getParent()为null
- Activity的View树中任何节点调用getRootView都是DecorView
- 通过类似inflate形成的View树,如下结构
View view = LayoutInflater.from(this).inflate(R.layout.title_bar,null);
使用布局是title_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_title_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title" />
</RelativeLayout>
- 非根节点也就是TextView,其getParent()是RelativeLayout,该View树中根节点为ReletiveLayout,其getParent()是null
- 该View树的任何View调用getRootView()都返回RelativeLayout
其实Activity View树只是所有View树中的一个特例。

549

被折叠的 条评论
为什么被折叠?



