调试 UI 的问题有时很棘手,Android Studio 4.0 内置了全新的布局检查器 (Layout Inspector),它的使用效果类似 Chrome 开发者工具,可以帮助开发者调试 Android 应用的 UI (用户界面)。布局检查器可用于设备和 Android 模拟器,它可以展示视图的层次结构。该工具有助于定位由根节点引起的问题。和上一个版本不同的是,新版本的布局检查器可以以三维的视角来展现视图层次结构,您可以直观地看到视图的布局方式。通过该工具您可以逐层来检查视图层次结构,同时它还会展示所有视图的属性,包括继承自视图父类的属性。
接下来我们一起了解一下最新版本的布局检查器是如何发挥作用的。首先点击窗口的 View 菜单,找到 Tool Window 子菜单,然后选择 Layout Inspector,这样就打开了布局检查器窗口。
如果您没有正在运行的进程,那么需要首先连接到一台设备或者启动一个 Android 模拟器实例,并且点击窗口的 Run 按钮来启动应用;
如果您的应用进程已经运行,点击 select process,选择正在运行的设备,然后从设备右侧的列表来选择一个已运行的应用。
Android 模拟器实例
https://developer.android.google.cn/studio/run/emulator
同样,您可以仅显示一个所选视图的父视图。
布局检查器示例
首先我们可以看到 LinearLayout 里布局了一个工具栏 (toolbar),然后是 navigation host。在它下面,您可以看到导航栏位于最下方——看来底部的导航栏被挤出了屏幕。
有可能是 navigation host 的尺寸设置错了,我们尝试把它的高度设置为 'wrap_content':
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:defaultNavHost="true"
android:layout_weight="9"
app:navGraph="@navigation/mobile_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="?android:attr/windowBackground"
app:menu="@menu/bottom_nav_menu" />
</LinearLayout>
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:defaultNavHost="true"
android:layout_weight="9"
app:navGraph="@navigation/mobile_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="?android:attr/windowBackground"
app:menu="@menu/bottom_nav_menu" />
</LinearLayout>
推荐阅读