Android 获取根视图

代码

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());

运行截图

在这里插入图片描述

结论

  • 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 里面写的布局
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,可以通过监听键盘的打开和关闭事件来获取键盘的高度。以下是获取键盘高度的步骤: 1. 创建一个 `ViewTreeObserver.OnGlobalLayoutListener` 监听器来监听布局的变化。 2. 获取布局的视图,然后添加上述监听器。 3. 在 `onGlobalLayout()` 方法中,检查键盘是否打开。如果打开,则获取键盘高度。 以下是示例代码: ``` private int keyboardHeight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final View rootLayout = findViewById(R.id.root_layout); rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); rootLayout.getWindowVisibleDisplayFrame(rect); int screenHeight = rootLayout.getRootView().getHeight(); int keyboardHeight = screenHeight - rect.bottom; if (keyboardHeight > 0) { // 键盘打开 // 保存键盘高度 MainActivity.this.keyboardHeight = keyboardHeight; } else { // 键盘关闭 // 清除键盘高度 MainActivity.this.keyboardHeight = 0; } } }); } ``` 在上述代码中,`root_layout` 是布局的 ID。在 `onGlobalLayout()` 方法中,首先获取当前窗口的可见区域,然后据屏幕高度和可见区域的底部位置计算键盘的高度。如果键盘高度大于 0,则说明键盘打开,保存键盘高度;否则键盘关闭,清除键盘高度。最后,可以在其他方法中使用 `keyboardHeight` 变量获取键盘高度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值