原文链接:https://medium.com/sebs-top-tips/tools-of-the-trade-part-2-b91271892d10

在上篇文章中我们了解到 tools 命名空间可以被用来只在写 xml 布局文件期间覆盖任何 attribute,也可以帮助我们更好地使用 Lint。当然,tools attributes 还有其他为我们所做的。


UI attributes

tools 命名空间剩下的所有 8 个 attributes 都是和 IDE 的 UI 预览面板有关,所以称之为 UI attributes。

这些 UI attributes 在你使用 IDE 写 layout 文件时会让一些工作更加简单方便。这些 attributes 包括:

  • tools:context
  • tools:menu
  • tools:actionBarNavMode
  • tools:listitem/listheader/listfooter
  • tools:showIn
  • tools:layout

The context attribute

context attribute 是用来告诉 IDE 你的 layout 文件是由哪个 Context 所解析。这样预览面板自动选择相应的主题,此外在 AS 中,在类文件中打开 Go to Related files 选项更准确得索引到 layout 文件。

attribute 的值为包含包名的 Activity,写在 layout 的根节点中:

1
2
3
4
5
6
7
8
9
10
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.example.MainActivity">
<!-- ... -->
</LinearLayout>

The menu attribute

menu attribute 用来告诉 IDE 预览面板中显示哪个 menu。同样的,写在 layout 的根节点中。

如果你使用了刚刚介绍的 context attribute 声明了对应的 activity,那 IDE 就会在 onCreateOptionsMenu 尝试检查出你所使用的 menu 文件,然后显示在预览面板上。但我们若使用了 menu attribute 的话,预览面板就会显示我们所声明的 menu。

在这个 attribute 中你可以定义一个或多个 menu 的 XML 文件,只需要写 menu 的文件名即可,以逗号隔开,形如:tools:menu="menu_main,menu_edit"

要不显示 menu,只要把值设空:tools:menu=""

还有一点需要注意的是,当你设置的主题基于 Theme.AppCompat 时,以上 attribute 就不起作用了。

The actionBarNavMode attribute

这个 attribute 用来确定预览面板中 Action Bar 应该显示何种的导航模式。有以下 3 种:

  • standard
  • tabs
  • list

ps:这个 attribute 在你使用基于 Theme.AppCompat 或 Theme.Material 的主题时、或你在 layout 中有使用 Toolbar 控件的时候是不起作用的。只有 app 是基于 holo 风格的主题才会有效。

The listitem, listheader and listfooter attributes

当在 layout 文件中有基于 AbsListView 的控件时,预览面板一般都只会显示常规的预览图。使用了 listitem、listheader 和 listfooter attributes 的话,你可以指定选择预览面板中显示 list items、header 和 footer 的 layout 文件。

1
2
3
4
5
6
7
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listheader="@layout/list_header"
tools:listitem="@layout/list_item"
tools:listfooter="@layout/list_footer" />

但是这里请注意,GridView 只有 listitem attribute 有效果。

当然,RecyclerView 使用以上的 attribute 也是没用的,它都不继承自 AbsListView 啊……

The layout attribute

这个 attribute 用来告诉预览面板在运行时哪个 layout 文件会被解析到一个 fragment(在 onCreateView()中)。它与你使用 include 标签的 layout attribute 相类似。

The showIn attribute

这个 attribute 适用于你使用 include 标签的 layout attribute 所指定的 layout 文件是以 merge 标签为根节点的情况。(介绍太长不翻了。。)

1
2
3
4
5
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="@layout/activity_main">

小结

tools 命名空间的使用为的是提高我们的开发效率,很多的工作都可以通过 IDE 帮我们来完成,何乐而不为呢?

引用博主的最后一句话:

Don’t be a tool, use the tools.