Android 获取根视图

举报
福州司马懿 发表于 2021/11/19 01:28:03 2021/11/19
【摘要】 代码 View decorView = getWindow().getDecorView(); View androidContent = findViewById(android.R.id.conte...

代码

View decorView = getWindow().getDecorView();
View androidContent = findViewById(android.R.id.content);
View androidContentFirstChild = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
View rootView = androidContentFirstChild.getRootView();

Log.i(TAG, "decorView: " + decorView.toString());
Log.i(TAG, "androidContent: " + androidContent.toString());
Log.i(TAG, "androidContent.getParent: " + androidContent.getParent());
Log.i(TAG, "androidContentFirstChild: " + androidContentFirstChild.toString());
Log.i(TAG, "rootView: " + rootView.toString());
Log.i(TAG, "decoView.getChildCount: " + ((ViewGroup)decorView).getChildCount());
Log.i(TAG, "androidContent.getChildCount: " + ((ViewGroup)androidContent).getChildCount());

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

运行截图

在这里插入图片描述

结论

  • decorView 与 rootView 是一个东西,都是页面的最顶层根布局,它有且仅有一个子视图
  • android.R.id.content 是一个 FrameLayout,里面才是我们在 layout 里面写的 xml 布局

Android Studio 查看布局结构

Tools ——> Layout Inspector,打开布局检查器对话框
在这里插入图片描述
注意,这里只有 debug 版本的 app 才可以查看布局的(第三方APP是无法查看的)
在这里插入图片描述
视图树

  • 最顶层是 DecorView,其下是一个 LinearLayout,包含了一个惰性布局的 ActionBar 和 FrameLayout 容器
  • 自带的 FrameLayout 的 id 固定为 android:id="@android:id/content",它的子布局才是我们在 xml 里面写的布局
    在这里插入图片描述

文章来源: blog.csdn.net,作者:福州-司马懿,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/chy555chy/article/details/107362236

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。