Android中xml的tools属性

Android 开发过程中,布局文件是可以直接在 IDE 中看到效果的,有时候有些布局的效果是根据网络请求的结果来展示,我们在写布局的时候,为了查看布局的美观,就直接写固定值了。

比如这种情况:TextView 在 xml 中没有设置任何字符,而是在 activity 中设置了 text。因此为了在 IDE 中预览效果,你必须在 xml 中为 TextView 控件设置 android:text 属性。

1
2
3
4
5
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />

有些布局界面可能是需要固定值,但是根据网络请求来显示的话,如果我们这样写忘记删除的话,就会导致一些问题,明明不应该显示的地方,确显示了,还得花时间去定位问题,即使没有显示问题,最终的产品中一直都有这种代码。

tools 属性

上面的情况,我们是有方法避免的,可以使用tools的命名空间和属性来解决这个问题。

1
2
3
4
5
6
7
8
9
10
xmlns:tools="http://schemas.android.com/tools"
...

<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Hello World" />

...

tools 属性可以告诉Android Studio ,这些属性在运行时是被忽略的,只在设计布局的时候有效。比如上面的例子,Hello World 只在设计布局的时候展示,运行后的界面是不会显示Hello World 的。

tools 可以覆盖 xml 布局中 android 的所有标准属性,将 android: 换成 tools: 即可。同时在运行的时候就连tools:本身都是被忽略的,不会被带进apk中。

tools 属性种类

tools 属性分为两种,一种是关于 xml 布局设计的,一种是影响 Lint 提示的,上面介绍的是 tools 最基本的用法,在 UI 设计的时候覆盖标准的 android 属性。下面介绍 Lint 相关属性。

Lint 相关属性

1
2
3
tools:ignore    ignore属性是告诉Lint忽略xml中的某些警告。
tools:targetApi
tools:locale
  • Lint会提示 ImageView 缺少 android:contentDescription 属性。我们可以使用 tools:ignore 来忽略这个警告

  • 假设minSdkLevel 15,而你使用了api21中的控件比如RippleDrawable,则Lint会提示警告。为了不显示这个警告,可以使用 tools:targetApi=”LOLLIPOP”。

  • 默认情况下 res/values/strings.xml 中的字符串会执行拼写检查,如果不是英语,会提示拼写错误,通过 tools:locale=”it” 来告诉studio本地语言不是英语,就不会有提示了。

PS: 关于忽略Lint 的属性,了解就好,一般不常用,也不影响编译。

参考文档