接下来我们一起了解一下最新版本的布局检查器是如何发挥作用的。首先点击窗口的 View 菜单,找到 Tool Window 子菜单,然后选择 Layout Inspector,这样就打开了布局检查器窗口。
- 如果您没有正在运行的进程,那么需要首先连接到一台设备或者启动一个 Android 模拟器实例,并且点击窗口的 Run 按钮来启动应用;
- 如果您的应用进程已经运行,点击 select process,选择正在运行的设备,然后从设备右侧的列表来选择一个已运行的应用。
该版本的布局检查器延续了之前版本的功能并且更加多样化。首先,布局检查器可以用两种方式显示 UI 层次结构: 以二维的轮廓格式,或者以一种称为旋转模式 (rotation mode) 的三维视图形式。
布局检查器示例
现在大家已经了解了布局检查器的使用方式。那么接下来我们通过实例来看一下如何使用它来解决应用的问题。这里我们有一个简单的示例应用,它包含一个 fragment,其中有一些静态文本和一个图片。如果您在阅读文章时想同步进行操作,可以先按照下面步骤操作创建工程。
- 打开 Android Studio 4.0,然后在 File 菜单里选择 New Project;
- 选择 Bottom Navigation Activity,点击 Next 然后点击 Finish;
- 替换 activity_main.xml 和 fragment_home.xml 的内容;
- 替换 HomeFragment.kt 的内容。
当您运行应用的时候,您会看到一个可爱的 android,但是里面少了一些东西: 底部的导航标签。看一下布局文件,我们可以看到底部的导航视图是存在的,但是屏幕却没有显示它。
有可能是 navigation host 的尺寸设置错了,我们尝试把它的高度设置为 'wrap_content':
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
<?xml version="1.0" encoding="utf-8"?>
<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>
回到布局检查器,您可以看到 LinearLayout 的尺寸正常了,但是底部的导航栏的位置不对:
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
<?xml version="1.0" encoding="utf-8"?>
<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>
然后得到如下结果:
快快尝试一下布局检查器的新特性,然后和我们分享您的使用体验吧。欢迎大家向我们反馈问题,或者告诉我们新的特性需求。
点击这里查看 Android 官方中文文档 —— 使用布局检查器调试布局