在开发Android项目的时候,xmlns:tools主要用在编译阶段,在打包时编译器会自动将tools相关的属性移除。具体来说,他负责具备功能:
- ①设计预览
- ②约束编码规则
- ③应对编译器检查
一、设计预览
1、常规属性预览
安卓开发中,在写布局代码的时候,ide可以看到布局的预览效果。但是有些效果则必须在运行之后才能看见,比如这种情况:TextView在xml中没有设置任何字符,而是在activity中设置了text。因此为了在ide中预览效果,你必须在xml中为TextView控件设置android:text属性
<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="我是一个好人" />
为了减轻工作量和开发负担,这里就要使用xmlns:tools辅助属性
<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="我是一个好人" />
其他Android的属性类似,我们在设计阶段只需要将android命名空间替换为tools命名空间。
2、页面片段组合预览
传统开发过程中,预览一个片段在整体中的效果,我们一般使用include,当然我们也可以使用tools:include。但是众多的片段中,聚焦到某一片段,我们推荐使用如下方式。
主页面
<fragment android:name="com.example.master.ItemListFragment"
tools:layout="@layout/list_content" />
fragment页面
tools:showIn="@layout/activity_main"
当然常见的有
tools:listitem
tools:listheader
tools:listfooter
tools:menu
二、约束编码规则
tools:context主要用来约束主题,当我们Manifest中Activity的主题切换,tools:context反向调整主题的预览效果。
此外,还能检测android:onClick对应的方法是否存在。
三、应对编译器检查
编译器对不合规的编码进行检查,但是这些不合规并不是错误,而是不符合规范。
- tools:ignore
- tools:targetApi
- tools:locale
tools:ignore
适合:任何元素
用于:Lint检查
这个属性接受一个以逗号分隔的lint问题id,达到忽略这个元素。例如,您可以告诉tools忽略MissingTranslation(缺失某语言的翻译)错误:
<string name="show_all_apps" tools:ignore="MissingTranslation">All</string>
tools:targetApi
适合:任何元素
用于:Lint检查
它的作用与@TargetApi一样。只是用于xml中。
例如,GridLayout在API level 14以上才支持:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:targetApi="14" >
当然,可以直接使用support v7库中的android.support.v7.widget.GridLayout
tools:locale
适合: <resources>
用于:Lint检查、Studio编辑器
在 <resources>中,为了避免拼写检查器的警告,可以使用tools:locale。它的值必须是一个有效的语言环境限定符
例如,在values/strings.xml中,表示默认字符串使用的语言是西班牙语,而不是英语:
<resources xmlns:tools="http://schemas.android.com/tools"
tools:locale="es">