想必 android 开发的小伙伴在布局文件中经常会看到 xmlns:tools="http://schemas.android.com/tools"

但是实际开发过程中我们却很少用到 tools 中的东西。

最近读了国外写的关于 tools 命名空间的博文,觉得很有必要写一篇中文版的。英文好的小伙伴直接去看原文吧~

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


在写 android 的 layout 文件时,我们经常会遇到这样一种情况:布局里有好多 TextView,但是又想在 IDE 中看到预览效果,怎么办?通常我们都会这样写:

1
2
3
4
5
6
7
<TextView
android:id="@+id/text_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.Title"
android:layout_margin="@dimen/main_margin"
android:text="I am a title" />

直接在 TextView 中写上假数据看效果,但是很有可能写完布局文件你就忘了删了。导致的结果就是上线的 app 很有可能让用户看到你写的假数据不知所云。如何解决?so easy:

1
2
3
4
5
6
7
<TextView
android:id="@+id/text_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.Title"
android:layout_margin="@dimen/main_margin"
tools:text="I am a title" />

只要改成上面这样,你既可以看到布局的预览图效果,也不会影响最终的 app。当然记得在布局文件的根标签加上 xmlns:tools="http://schemas.android.com/tools"


tools attributes 其实可以被分为两类。第一类包含了所有的 attributes,会影响到 Lint analysis;第二类包含了其他的一些 attributes,会影响使用 IDE 编写 XML 的时候。

Lint attributes

在 tools 命名空间中有 3 种 Lint attributes:

  • tools:ignore

  • tools:targetApi

  • tools:locale

The ignore attribute

这个 ignore attribute 基本等同于 Java 中的@SuppressWarnings 注解,告诉 Lint 忽略某方面的警告信息。比如我们有个 ImageView 没有设置 android:contentDescription,在 XML 中 Lint 就会有警告信息。我们可以加上 ignore attribute 来去除 Lint 的警告:

1
2
3
4
5
6
7
8
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/margin_main"
android:layout_marginTop="@dimen/margin_main"
android:scaleType="center"
android:src="@drawable/divider"
tools:ignore="contentDescription" />

The targetApi attribute

这个 attribute 等同于 Java 中的@TargetApi 注解,用来告诉 Lint 你在 XML
中使用的某一控件的最低 API 版本(这句直接从英文翻译过来,感觉解释不清楚)。举例子,你在 drawable 文件夹(未标记为-v21)下的一个 layout 文件中写了 5.0 才有的 ripple 控件:

1
2
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/accent_color" />

这样写在通用的 drawable 下 Lint 肯定会报警告信息,如果你确定已经在 API20 以下的版本时会使用其他的 layout,那你可以使用 targetApi attribute 消除 Lint 警告:

1
2
3
4
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:color="@color/accent_color"
tools:targetApi="LOLLIPOP" />

The locale attribute

最后一个 attribute 是用来标明一个 resource 是针对某一地区的。这个属性在 tools 命名空间里用的很少。如果你的应用只针对说意大利语地区的人,那你在 res/values/strings.xml 可以这么写:

1
2
3
4
5
6
7
8
<resources
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:locale="it">

<!-- Your strings go here -->

</resources>

这样 Android Studio 就知道你的 app 语言不是以英语为主,而且在 strings.xml 中不会进行 spell check。